C++ 找不到运算符

标签 c++ operators

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

最佳答案

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

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

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

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

这是一个 interesting discussion以更好地理解该主题。

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

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

bucket_string(bucket_string&& other);
bucket_string& operator=(bucket_string&& other);

关于C++ 找不到运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15631731/

相关文章:

c++ - 提升 C++ 与 Python 的能力

java - 用于成员访问的 '.' 是否被视为 Java 中的运算符?

c++ - 为什么在 C++ 中使用 std::atomic<double>、std::atomic<float> 时,compare_exchange_strong 会失败?

c++ - 测序完整性检查

c++ - 使用 C++ 插件从 chrome 浏览器下载并运行 exe

C++ 仅实现模板类

c++ - 使用 '&&' 而不是 'and' 运算符编码

c# - 两个左尖括号 "<<"在 C# 中是什么意思?

c - 为什么输出是 6 而不是 7?

c# - 覆盖对象的虚拟方法