【发布时间】:2017-03-31 04:01:21
【问题描述】:
在下面定义的名为 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";
}
error: conversion from 'const char [38]' to non-scalar type 'foo' requested
上述错误仅在我为带有声明的对象实例赋值时引起,但如果我与声明分开赋值,则重载的等于 = 运算符工作正常。
我想用任何方法将字符串分配给对象使用相等运算符
和作为声明,如foo a = "abcd";
【问题讨论】:
-
你需要一个转换构造函数,即
foo(const std::string& s) : str(s) {} -
失败的代码不是“给对象赋值...”而是试图初始化对象,这需要一个构造函数。
-
您需要从 const char* 构建构造函数。
标签: c++ c++11 initializer