【问题标题】:Copy Constructor Error: returning a value from a constructor复制构造函数错误:从构造函数返回值
【发布时间】:2015-02-27 02:44:25
【问题描述】:

我可能刚刚做了一些愚蠢的事情,但我无法在任何地方找到此错误消息的答案。

我遇到的问题是我不断收到错误 “从构造函数返回一个值”

我这里的代码是一个拷贝构造函数:

RealBox::RealBox(const RealBox& rhs)
{
  if(this != &rhs)
  {
    m_boxsize = rhs.m_boxsize;
    delete[] m_reals;
    m_reals = new float [m_boxsize];

    for(int i=0;i<m_boxsize;i++)
    {
      m_reals[i]=rhs.m_reals[i];
    }
  }
  return *this;
}

来自一个班级:

class RealBox
{ 
  private:  
    float* m_reals;                     // Array of Real Numbers
    int m_boxsize;                      // number of Real Numbers    


public:
  RealBox(int s, float a);
  ~RealBox();
  const RealBox& operator=(const RealBox& rhs);

  // Purpose: Copy Constructor
  // Parameters: rhs - RealBox to be copied
  // Postconditions:  *this == rhs
  RealBox(const RealBox& rhs);

  void set( int i, float x);
  friend std::ostream& operator<< (std::ostream& out, 
                               const RealBox& box);
};

我确定我刚刚做了一些愚蠢的事情,但我无法弄清楚,任何帮助将不胜感激。

【问题讨论】:

  • 从字面上看,不允许从构造函数返回值。
  • 错误信息的哪一部分你不明白?
  • 也许您正在考虑另一种语言,例如 C?
  • 是的,我刚刚弄清楚发生了什么(我也不得不删除,删除)对不起,我是个菜鸟

标签: c++ compiler-errors copy-constructor deep-copy


【解决方案1】:

从你的复制构造函数中去掉return *this;。

PS - 我认为复制构造函数传递对*this 的引用是无效的,因此您不必防范它。如果它以某种方式发生,则要从中复制的传递参数本身没有构造,或者您正在重新构造一个已经构造的对象。无论哪种方式都是错误的。

【讨论】:

    【解决方案2】:

    不要在复制ctor中返回。

    return *this;是错误的。

    我认为你把赋值运算符和复制构造函数混淆了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-07
      • 2013-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多