c++ - 为什么复制构造函数只能接受一个引用参数?

标签 c++

<分区>

我正在学习 C++,这是我第一次尝试了解复制构造函数的工作原理:

class Cents
{
private:
    int m_nCents;
public:
    Cents(int nCents=0)
    {
        m_nCents = nCents;
    }

    // Copy constructor
    Cents(  Cents cSource)
    {
        m_nCents = cSource.m_nCents;
    }
};

int main()
{
 Cents cMark(5); // calls Cents constructor
 Cents cNancy = cMark; // calls Cents copy constructor!
 return 0;
}

但是我得到这个错误:

Error 1 error C2652: 'Cents' : illegal copy constructor: first parameter must not be a 'Cents'

我的复制构造函数有什么问题?

我检查过如果在构造函数中我通过引用传递参数,那么它编译得很好,但不会按照我正在做的方式工作。为什么会这样?

最佳答案

按值传递任何参数都需要复制构造函数 - 显式或隐式。 当我们定义一个复制构造函数时,我们的意思是我们不想使用隐式复制构造函数。 为复制构造函数使用定义的复制构造函数会产生循环依赖。

关于c++ - 为什么复制构造函数只能接受一个引用参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28134178/

相关文章:

c++ - 缓慢移动的 3D 球体到 3D 三角形碰撞

c++ - 函数修复 "was not declare in this scope"

python - 如何在cython中使用并行性

c++ - 当我使用 expire_at 时,Boost deadline_timer 没有生成事件?

c++ - 如何在 c++(0x) 中使用多个返回值进行初始化

c++ - 为什么 `typeid(T&).name()` 的输出给出为 `T` 而不是 `T&` ?

c++ - 知道任何好的 c++ 支持 vector 机 (SVM) 库吗?

c++ - 编译pimpl成语代码的问题

c++ - Windows 上最快的屏幕捕获方法

c++ - vector <bool> 迭代器不可解引用