带字符串参数的重载赋值运算符 我有C++中定义的一种类型: class MyTypeT { public: MyTypeT(); virtual ~MyTypeT(); /// Initialize from string bool fromString(const std::string &typeinfo); /// Write to string virtual std::string toString() const; /// Is instance empty (not initialized yet) bool empty() const; };
我想让赋值操作符过载,如下所示:带字符串参数的重载赋值运算符 我有C++中定义的一种类型: class MyTypeT { public: MyTypeT(); virtual ~MyTypeT(); /// Initialize from string bool fromString(const std::string &typeinfo); /// Write to string virtual std::string toString() const; /// Is instance empty (not initialized yet) bool empty() const; };,c++,operator-overloading,C++,Operator Overloading,我想让赋值操作符过载,如下所示: MyTypeT & MyTypeT::operator=(const std::string & rhs) { fromString(rhs); return *this; } 这是允许且有用的方法,还是有任何副作用?相关/重复:最好创建MyTypeT(std::string)constructor,并且不需要为您键入和std::string以及任何其他运算符多次重载。允许:是。有用:不。@ChristianHackl为什么不呢
MyTypeT & MyTypeT::operator=(const std::string & rhs)
{
fromString(rhs);
return *this;
}
这是允许且有用的方法,还是有任何副作用?相关/重复:最好创建
MyTypeT(std::string)
constructor,并且不需要为您键入和std::string
以及任何其他运算符多次重载。允许:是。有用:不。@ChristianHackl为什么不呢?取决于你的代码如何使用这个类,这可能是个好主意,也可能不是个好主意。作为一个粗略的经验法则,如果您提供一个操作符=()
,那么您需要提供一个相应的构造函数。