我在调用基本拷贝构造函数时收到错误

时间:2012-01-17 00:13:39

标签: c++ inheritance

我在尝试明确调用基本副本ctor时接收此代码中的error C2082: redefinition of formal parameter 'rval'

 #include <iostream>
 using namespace std;


class Base
{
public:
    Base(const Base& rhs){ cout << "base copy ctor" << endl; }
};

class Derived : public Base
{
public:
    Derived(const Derived& rval) { Base(rval) ; cout << "derived copy ctor" << endl; }
      // error C2082: redefinition of formal parameter 'rval'
};

int main()
{
    Derived a;
    Derived y = a; // invoke copy ctor
    cin.ignore();
    return 0;
}

但是,如果这样做:

Derived(const Derived& rval) { Base::Base(rval) ; cout << "derived copy ctor" << endl; }

然后就可以了。

我为什么这么问? 根据{{​​3}}

的答案

我不必使用运算符::来访问基本副本ctor, 那我为什么会收到这个错误?

btw:我正在使用visual studio 2010。

我还有一个问题:

我是否必须在派生类的用户定义移动构造函数中调用base的移动构造函数?

2 个答案:

答案 0 :(得分:2)

要调用基础构造函数,您需要将调用放在成员初始化列表中

class Derived : public Base
{
public:
    Derived(const Derived& rval) : Base(rval)
    { 
         cout << "derived copy ctor" << endl;
    }
};

答案 1 :(得分:1)

假设你的意思是'move'构造函数是复制构造函数 - 是的。您将不得不调用Base的构造函数。否则,定义是否派生对象中的基础对象不完整。您可以调用复制构造函数或基类的普通构造函数。