gpt4 book ai didi

使用 operator= 的 C++ 对象构造

转载 作者:行者123 更新时间:2023-11-30 03:53:01 25 4
gpt4 key购买 nike

我是这样维护三的规则的--

// actual constructor
stuff::stuff(const string &s)
{
this->s_val = s[0];
this->e_val = s[s.length() - 1];
}

// copy constructor
stuff::stuff(const stuff &other)
{
this->s_val = other.s_val ;
this->e_val = other.e_val ;
}

// assignment
stuff& stuff::operator=(const stuff &other)
{
stuff temp(other);
*this = move(temp);
return *this;
}

现在我可以这样调用了--

stuff s1("abc");
stuff s2(s1);
stuff s3 = s2 ; // etc ...

现在我正在尝试实现一个将使用 operator= 的函数,这样我就可以调用 --

stuff s;
s = "bcd" ;

我是这样写的--

stuff& stuff::operator=(const string &s)
{
stuff temp(s);
*this = move(temp);
return *this;
}

但它给我段错误。另外想调用like怎么办

stuff s = "bcd" ?

我该怎么做?

最佳答案

你的赋值运算符和复制构造函数看起来应该是一样的:

stuff& stuff::operator=(const stuff &other)
{
this->s_val = other.s_val ;
this->e_val = other.e_val ;
return *this;
}

您不能用另一个 = 运算符定义您的 = 运算符。记住,std::move 没有做任何特殊的魔法,它只是将一个变量变成可以使用移动语义来计算的东西。您仍然需要将您的函数定义为首先处理 r-value-reference 的函数,而您没有这样做(您没有任何移动赋值运算符)。

在接受字符串的 = 运算符中,您可以使用常规运算符:

stuff& stuff::operator=(const string &s)
{
*this = stuff(s);
return *this;
}

更多建议:你的 this-> 是多余的。编译器知道您引用的变量是 this 的一部分。还有,行:

this->s_val = s[0];
this->e_val = s[s.length() - 1];

可以更优雅地写成:

s_val = s.first();
e_val = s.back();

顺便说一句。复制构造函数、赋值运算符和析构函数也是冗余的。三(或五,如 C++11)的规则说 *IF* 你实现了任何复制 ctor。赋值运算符或析构函数 - 您需要全部实现它们。问题是,您应该首先实现其中的任何一个吗?你在这里没有任何动态分配,没有浅层复制,也没有什么特别需要特殊成员函数(复制构造函数等)。您不妨删除整个三个,这将是您示例中的最佳情况。

关于使用 operator= 的 C++ 对象构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30343406/

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