使用 operator= 的 C++ 对象构造
c++ object construction using operator=
我是这样维持三的规律的--
// 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* you implement any of the copy ctor. assigment operator or the destructor - you need to implement them all.
问题是,您应该首先实施其中的任何一个吗?你在这里没有任何动态分配,没有浅层复制,也没有什么特别需要特殊成员函数(复制构造函数等)。
您不妨删除整个三个,这将是您示例中的最佳情况。
我是这样维持三的规律的--
// 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* you implement any of the copy ctor. assigment operator or the destructor - you need to implement them all.
问题是,您应该首先实施其中的任何一个吗?你在这里没有任何动态分配,没有浅层复制,也没有什么特别需要特殊成员函数(复制构造函数等)。
您不妨删除整个三个,这将是您示例中的最佳情况。