在如下定义的名为foo的类中
class foo{
private:
string str;
public:
foo operator = (string s){
str = s;
}
};
int main(){
foo a = "this initialization throwing an error";
foo b;
b = "but assignment after declaration is working fine";
}
错误:请求从“const char [38]”转换为非标量类型“foo”
上述错误仅在我通过声明为对象实例赋值时引起,但如果我与声明分开赋值,则重载的等于 =
运算符工作正常。
我想在任何方法中使用相等运算符将字符串分配给对象
和作为声明,例如foo a = "abcd";
最佳答案
当你有
type name = something;
你不是在做赋值,而是你有复制初始化(不要以为可以有移动,即使它被称为复制)。这意味着您的类中需要一个构造函数,其参数与 =
右侧的参数相匹配。
在这种情况下,您没有采用 std::string
、const char*
或 const char[]
的构造函数,所以编译器无法在那里构造实例。
第二种情况有效的原因是
b = "but assignment after declaration is working fine";
没有尝试构造任何东西,因此它调用了确实有效的赋值运算符,因为
"but assignment after declaration is working fine"
可以转换为 std::string
。
如果您希望您的类可以从字符串文字或 cstring 构造,那么您可以以以下形式向其添加构造函数
foo(const char* str) : str(str) {}
关于c++ - 使用相等运算符初始化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40640877/