gpt4 book ai didi

C++ : In Class Assignment operator function why do we have to return *this

转载 作者:行者123 更新时间:2023-11-30 02:44:32 29 4
gpt4 key购买 nike

<分区>

我用 C++ 编写了一个类并定义了赋值运算符函数:cplusplus.com 推荐以下语法。

check operator= (const check& obj){*cstr = *(obj.cstr); return *this;}

另一种语法是:

void operator= (const check& obj){*cstr = *(obj.cstr);} # Not returning *this

您会推荐使用第一种方法还是第二种方法?

以下是我的类(class):

class check {
private:
string * cstr;
public:
int a;
check (string str) { cstr = new string(str);}
check (const check& obj) {cstr = obj.cstr;}
~check() {cout<<"DES"<<endl; delete cstr; }
check operator= (const check& obj){*cstr = *(obj.cstr); return *this;}
void display () { cout<<*cstr<<endl;}
};

int main () {
check da {"one"};
check pa {"two"};
pa = da;
have (pa);
return 0;
}

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com