我有简单的代码。
template<typename T>
class NamedObject{
public:
NamedObject(std::string& name, const T& value):nameValue(name), objectValue(value)
{
}
private:
std::string& nameValue;
const T objectValue;
};
int main(int argc, char* argv[])
{
NamedObject<int> no1("Smallest Prime Number",2);//error
NamedObject<int> no2(std::string("Smalledst Prime Number"),2);//works
return 0;
}
当我将第一个参数设为非引用时,no1 和 no2 对象都会被创建。但是当我继续引用 Visual Studio 编译器时会出现以下错误,
Error 1 error C2664: 'NamedObject::NamedObject(std::string &,const T &)' : cannot convert parameter 1 from 'const char [22]' to 'std::string &' c:\users\pkothari\documents\visual studio 2008\projects\stackoflw\stackoflw\stackoflw.cpp 36
如果 char * 可以转换为 std::string,为什么不转换为 std::string& 呢?有什么办法让它发挥作用吗?
最佳答案
NamedObject<int> no2(std::string("Smalledst Prime Number"),2);//works
这不应该在符合标准的编译器中工作。它在 MS Visual Studio C++ 中受支持,即使它不是标准的 C++。
当预期参数为 std::string&
时,以下调用均无效。
NamedObject<int> no1("Smallest Prime Number",2);
NamedObject<int> no2(std::string("Smalledst Prime Number"),2);
当参数类型为 std::string
或 std::string const&
时,它们都应该工作。
关于c++ - 为什么 std::string 引用不能带 char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44275742/