2017-06-01 73 views
0

我正在使用以下代码进行原型设计。为什么将char *传递给字符串参数会产生编译错误?

#include <vector> 
#include <iostream> 
#include <algorithm> 
#include <string> 


template<class container, class value> class Add { 
public: 
    Add(){}; 
    ~Add(){}; 
    void add_value(container& cont, value& val){ 
     std::for_each(cont.begin(), cont.end(), [&val](value& v){v +=val;}); 
    }; 
}; 


int main(int argc, char const *argv[]) 
{ 
    Add<std::vector<std::string>, std::string> a; 
    std::vector<std::string> vec = {"a", "b", "c", "d"}; 
    std::string foo= "1"; 
    a.add_value(vec, foo); // compiles fine 
    a.add_value(vec, "1"); // generates an error 
    return 0; 
} 

,我得到了以下错误

template.cpp:28:25: error: invalid initialization of non-const reference of type ‘std::__cxx11::basic_string<char>&’ from an rvalue of type ‘std::__cxx11::basic_string<char>’ 

为什么它不可能通过一个char*string说法?

据我所知,为了将char*转换为std::string并将结果传递给该函数,将执行一个隐式转换。

+6

功能需要采取一个const引用。非const引用不能绑定到临时对象,比如将“1”转换为字符串所产生的临时对象。错误消息告诉你。 –

+0

我在这里很好奇。为什么非const引用不能绑定到右值? – hannibal

+0

因为C++标准没有说。 –

回答

4

您定义的add_value如下:

void add_value(container& cont, value& val) 

凡字符串是一个非const引用,编译器期望此引用指向一个修改变量别的地方。

但是,当您传递const char[]时,即使此类型可以转换为字符串(以防编译),它仍会动态完成,且字符串不可修改。实际上,char*也不可修改。这就是为什么你的代码不能编译。

你可以定义你的函数如下,它会工作:

void add_value(container& cont, const value& val) 
+3

不是我,但你有几件事情有点不对:''1“'不是'char *',而是'const char []'。它可以衰减到'const char *',但永远不会是'char *'。此外,它不编译的原因不是因为字符串文字不可修改,而是因为OP试图将一个prvalue绑定到一个左值引用。 – Rakete1111

+2

您的短语“即使此类型可以转换为字符串”也意味着它不能。实际上,'const char *'(或者,实际上是const char [2]')可以转换为'std :: string',这就是为什么只要将参数设置为'const&'的原因。 –

+0

感谢您的反馈。 @ Rakete1111:不确定字符串文字是否是prvarlue,我错过了什么? –

相关问题