今天测试一段代码时遇到报错:
**重点是这句“no known conversion from ‘const char [[4]]’ to ‘std::__cxx11::string &’ (aka ‘basic_string &’) for 1st argument……”
代码如下:**
h文件中声明类如下:
class Person
{
public:
Person( string &name, int age);
virtual ~Person();
virtual void func();
private:
PersonImpl *mPersonImpl;
};
man函数中:
int main()
{
Person *people = new Person("Tom", 12);
return 0;
}
报错原因:
把函数不会改变的形参定义为(普通的)引用【应为const引用】是一种比较常见的错误。
导致[1]:
1.误导函数可以修改它的实参的值;
2.极大限制函数所能接受的实参类型【不再能接受const对象、字面值、需要类型转换的对象】
解决:
Person( string &name, int age);
Person(const string &name, int age); //修改为常引用
或者:
string str("Tom");
Person *people = new Person(str, 12); //传string对象,而非字面量
参考文献:
[1] https://blog.csdn.net/goldcarpenter/article/details/81975241