2013-03-26 121 views
4

有人可以告诉我为什么这不起作用吗?我的印象是,C++会自动将值返回值函数结果的引用传递给构造函数,但它抱怨没有找到匹配的运算符。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

我很惊讶,你没有得到有关敌不过一个错误的'bucket_string :: bucket_string(为const char *)'。这是你的完整代码吗?另外,“迭代器”在哪里声明? – 2013-03-26 07:40:02

+0

不,它不是 - 我去掉大部分,使其更易于阅读和回答我的问题:-) – Supremacy 2013-03-26 07:44:52

+0

你的示例代码应该是完整的,以及最小的和你显示的错误应该来自于你实际有代码在你的问题中没有你没有显示的一些不同的代码。这样做会使问题答案成为帮助您解决实际问题的战斗机会。 – 2013-03-26 07:49:30

回答

7

在C++中,临时值不​​能被结合到非const引用。

bucket_string substr(iterator start, iterator end)函数返回一个临时的,和你的构造/分配运营商采取非const引用作为参数,因此你的问题。

因此,你需要将丢失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); 
+0

@Tushar:哼......什么? – ereOn 2013-03-26 07:47:42

+0

该链接中的答案使其更清晰一点,谢谢。 – Supremacy 2013-03-26 07:50:26

+0

@Supremacy:很高兴能帮到你。 – ereOn 2013-03-26 07:53:23

6

把一些const

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

您正在向构造函数传递一个临时const值。编译器正在搜索其accpets const参考构造:

bucket_string bs("the quick brown fox jumps over the lazy dog"); 
+7

你应该真的解释为什么需要'放置一些const'。这不是关于“传递const值”。 – juanchopanza 2013-03-26 07:39:35

+1

值得一提的是临时表不能被绑定到非const引用。 – ereOn 2013-03-26 07:39:54

+0

完全是,“把一些常量的地方,也许能帮助” – 4pie0 2013-03-26 07:40:10

1

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

​​

此操作,因为C++将允许临时对象(例如,函数的返回值),以通过一个const引用传递。

如果你实际上要修改的赋值操作的来源,那么C++提供了右值引用的解决方案。而不是const &使用&&。但分配将不再幂等,所以它会被称为移动分配和使用 - 临时对象时,你会需要替代语法。