有人可以告诉我为什么这不起作用?我的印象是C++会自动将返回值函数结果的引用传递给构造函数,但它抱怨没有找到匹配的运算符.
class bucket_string {
public:
bucket_string();
bucket_string(bucket_string & rhs);
bucket_string & operator=(bucket_string & rhs);
virtual ~bucket_string();
bucket_string substr(iterator start, iterator end){
bucket_string b(str);
return b;
}
};
bucket_string bs("the quick brown fox jumps over the lazy dog");
bucket_string bs1 = bs.substr(bs.begin(), bs.end());
Run Code Online (Sandbox Code Playgroud)
返回以下错误:
error: no matching function for call to ‘bucket_string::bucket_string(bucket_string)’
note: candidates are: bucket_string::bucket_string(bucket_string&)
bucket_string::bucket_string()
Run Code Online (Sandbox Code Playgroud)
在C++中,临时值不能绑定到非const引用.
你的bucket_string substr(iterator start, iterator end)函数返回一个临时的,你的构造函数/赋值运算符将非const引用作为参数,因此你的问题.
因此,您需要将缺少的const说明符添加到构造函数和赋值运算符中.像这样:
bucket_string(const bucket_string& rhs);
bucket_string& operator=(const bucket_string& rhs);
Run Code Online (Sandbox Code Playgroud)
以下是关于该主题的有趣讨论,以便更好地理解.
另外,如果C++ 11是一个选项,你也可以让你的类可以移动.这将允许临时的内部资源转移到另一个实例.如果在你的情况下这是一件好事,我们缺乏背景.
然后,您必须实现这些方法:
bucket_string(bucket_string&& other);
bucket_string& operator=(bucket_string&& other);
Run Code Online (Sandbox Code Playgroud)
放一些const.
bucket_string(const bucket_string & rhs);
^^^^^
bucket_string & operator=(const bucket_string & rhs);
^^^^^
Run Code Online (Sandbox Code Playgroud)
您正在将临时const值传递给构造函数.编译器正在搜索一个接受const引用的构造函数:
bucket_string bs("the quick brown fox jumps over the lazy dog");
Run Code Online (Sandbox Code Playgroud)