c++ - 为什么 std::string 引用不能带 char*?

标签 c++ string reference

我有简单的代码。

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::stringstd::string const& 时,它们都应该工作。

关于c++ - 为什么 std::string 引用不能带 char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44275742/

相关文章:

c++ - 局部变量引用其他局部变量是否危险?

c++11 - 完美转发导致错误我不明白

c++ - 是否有任何巧妙的方法可以从数组 vector 中获取指向数据的指针?

c++ - 'mem_fun' : is not a member of 'std'

c++ - 使用vs2015社区encog-c编译报错

c - 在C中将字符串读入二维数组

ios - 引用由另一个函数创建的数组

c++ - Qt 模糊 QMovie(来自 gif)

r - 在 R 中使用 apply 函数进行字符串连接

python - 如何将字符串列表更改为整数 - Python