4

有人可以告诉我为什么这不起作用吗?我的印象是 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());

返回以下错误:

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()
4

3 回答 3

7

在 C++ 中,临时值不​​能绑定到非常量引用。

您的bucket_string substr(iterator start, iterator end)函数返回一个临时值,并且您的构造函数/赋值运算符将非常量引用作为参数,因此您的问题。

因此,您需要将缺少的const说明符添加到构造函数和赋值运算符中。像这样:

bucket_string(const bucket_string& rhs);
bucket_string& operator=(const bucket_string& rhs);

这是一个关于该主题的有趣讨论,以便更好地理解。

附带说明一下,如果 C++11 是一个选项,您也可以使您的类可移动。这将允许您临时的内部资源转移到另一个实例。我们缺乏上下文来说明这在您的情况下是否是一件好事。

然后你必须实现这些方法:

bucket_string(bucket_string&& other);
bucket_string& operator=(bucket_string&& other);
于 2013-03-26T07:41:56.400 回答
6

Put some const.

bucket_string(const bucket_string & rhs);
              ^^^^^
bucket_string & operator=(const bucket_string & rhs);
                          ^^^^^

You're passing a temporary const values to the constructor. Compiler is searching for a constructor which accpets const reference:

bucket_string bs("the quick brown fox jumps over the lazy dog");
于 2013-03-26T07:37:46.050 回答
1

代码以一种不起作用的方式混合了值和引用语义。substr按值返回,但构造函数通过非常量引用获取参数。非常量表示参数将被视为可修改的对象,而不是纯值。语言禁止以这种方式使用引用。调整赋值运算符,使其不能修改其参数:

        bucket_string & operator=(bucket_string const & rhs);

这是可行的,因为 C++ 将允许通过const引用传递临时对象(例如函数返回值)。

如果您确实想修改赋值操作的来源,那么 C++ 提供了右值引用的解决方案。而不是const &使用&&. 但是分配将不再是幂等的,因此它被称为移动分配,并且在使用临时对象时需要替代语法。

于 2013-03-26T07:44:55.430 回答