操作符重载2

&&和||操作符也可以重载,但是不建议重载因为重载时短路与和短路或都会‘失效’,即不论实际第一个表达式为true还是false,短路与和短路或后面的表达式都会继续判断,这样会导致结果和预期可能不同!

 1 //对于标准数据类型直接使用&&和||
 2 //假设+操作符已经重载
 3 
 4 Test t{
 5 public:
 6     Test(int a){
 7         this->a=a;
 8     }
 9     bool operator&&(Test &another){
10         if(this->a && another.a){
11             return true;
12         }
13         else{
14             return false;
15         }
16     }
17 private:
18     int a;
19 }
20 
21 int main(void){
22     int a = 0;
23     if (a && (a = 1)
24     {
25         cout<<"true..."<<endl;
26     }
27     cout<<a<<endl;//因短路与的关系,此时a=0
28 
29     Test t1(0);
30     Test t2(1);
31     if (t1 && (t1 + t2)
32     {
33         cout<<"true..."<<endl;//即使t1为false,(t1 + t2)也执行了
34     }
    return 0;
35 }

 =操作符重载注意:

  1. 判断是否为自身;

  2. 自身不为空时需要释放空间;

  3. 重新开辟空间实现深拷贝;

  4. 返回自身*this;

  详见下面代码:

MyString& MyString::operator=(const MyString &another) {
    if (this == &another) {
        return *this;
    }
    if (this->str != NULL) {
        delete this->str;
        this->str = NULL;
        this->len = 0;
    }
    this->len = another.len;
    this->str = new char[this->len + 1];
    strcpy(this->str, another.str);

    return *this;
}

 

posted @ 2018-12-05 08:14  zarjen  阅读(120)  评论(0编辑  收藏  举报