c++中发现的一些问题

#include<iostream>
using namespace std;
class test
{
private:
    int a,b;
public:
    test(int aa=0,int bb=0,int cc=3):c(cc)//常数据成员只能用初始化列表
                                        //而且其值不能被更新
    {
        a=aa;
        b=bb;
    }
    test operator +(test & t)
    {
        return test(a+t.a,b+t.b);
    }
    test & operator =(const test &t)//只能用常引用或直接值传递。原因见下
    {
        a=t.a;
        b=t.b;
        return *this;
    }
    void set(int aa,int bb)
    {
        a=aa;
        b=bb;
    }
    void show()const
    {
        cout<<"a: "<<a<<" b: "<<b<<endl;
    }
    const  int c;
};
int ff()
{
    return 2+2;
}
int main()
{
    //test t();//晕!这不是以空初始化一个对象。而是声明一个以test为返回值的不带参数的
     test t;//后不能跟括号。原因见上
    //函数。相当于
    int tt(void);
    int (*f)();//复习了下函数的指针
    f=ff;
    cout<<f()<<endl;
    test s(1,2),q;

    q=s+t;//s+t返回值为一个零时对象。系统会将其视为常对象处理。
    //因此只能与常引用而不能将其与非常引用绑定。
    const test & p=(s+t);//没有const将报错
    p.show();//常引用所绑定对象将被视为常对象看待
    //其只能调用其常函数。和访问常数据成员;
    cout<<"c: "<<p.c<<endl;;
    return 0;
}

/*
感谢这位同学错误代码给我的启示
#include<iostream>
using namespace std;

class Rectangle
{
private:
    double x1,x2,y1,y2;
public:
    Rectangle(double t1=0,double t2=0,double m1=0,double m2=0)
    {
        assign(t1,t2,m1,m2);
    }
    Rectangle()
    {}
    void assign(double t1,double t2,double m1,double m2)
    {
        x1=t1;
        x2=t1;
        y1=m1;
        y2=m2;
    }
    void show()
    {
        cout<<"矩形左上角的坐标:"<<"("<<x1<<","<<y1<<")"<<endl;
        cout<<"矩形右下角的坐标:"<<"("<<x2<<","<<y2<<")"<<endl;
    }
    Rectangle operator+(Rectangle&p)
    {
        return Rectangle(x1+p.x1,x2+p.x2,y1+p.y1,y2+p.y2);
    }
    Rectangle operator-(Rectangle&p)
    {
        return  Rectangle(x1+p.x1,x2+p.x2,y1+p.y1,y2+p.y2);
    }
    Rectangle operator=(Rectangle &t)
    {
        x1=t.x1;
        x2=t.x2;
        y1=t.y1;
        y2=t.y2;
        return *this;
    }
};

int main()
{
    Rectangle rect(100,200,300,400);
    cout<<"初始rect:"<<endl;
    rect.show();
    cout<<endl;
    rect.assign(100,200,300,400);
    cout<<"赋值后rect:"<<endl;
    rect.show();
    Rectangle s(),t(1,4,16,22);
    s=rect-t;
    s.show();
    cout<<endl;
    s=rect+t;
    s.show();
    return 0;
}
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值