c++ - 复制构造函数错误 : returning a value from a constructor

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

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

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

我这里的代码是一个复制构造函数:

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):

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);
};

我确定我刚刚做了一些愚蠢的事情,但我想不通,任何帮助将不胜感激。

最佳答案

从复制构造函数中删除 return *this;

PS - 我认为向复制构造函数传递对 *this 的引用是无效的,因此您不必针对它进行保护。如果它以某种方式发生,要么要从中复制的传递参数本身未构造,要么您正在重新构造一个已经构造的对象。无论哪种方式都是错误的。

关于c++ - 复制构造函数错误 : returning a value from a constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28756661/

相关文章:

c++ - 在 C++ 中对字符串使用复制构造函数和/或赋值运算符时发生堆栈溢出

c++ - 在 QT5 中使用 QProcess 运行 gcc

用于旧 gcc 的 C++ 模板在 clang++ 中导致 'shadows template parameter' 错误

c++ - 访问使用不同模板参数实例化的模板类的成员

java - 如何让 "circular"泛型在 Java 中工作?

c++ - 在 C++ 中返回自动本地对象

c++ - 程序崩溃并且不显示正确的输出

c++ - Qt - qstring.h 包含字符串错误

c++ - "Does not name a type"类错误

c++ - 在结构的 STL 映射中,为什么 "[ ]"运算符会导致结构的 dtor 被额外调用 2 次?