【问题标题】:I'm receiving error when calling base copy constructor调用基本副本构造函数时收到错误消息
【发布时间】:2012-01-17 00:13:38
【问题描述】:

在尝试显式调用基本副本 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; }

然后就可以了。

我为什么要问这个? 根据StackOwerflow上的答案

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

顺便说一句:我正在使用 Visual Studio 2010。

我还有一个问题:

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

【问题讨论】:

    标签: c++ inheritance


    【解决方案1】:

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

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

    【讨论】:

    • 哦!是的 :D 我怎么忘记了,哈哈,你能回答我的第二个问题吗?非常感谢!
    • @codekiddy 我不知道你是否必须显式调用基类ctor的确切规则,但作为个人规则,我总是显式调用基类ctor .
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-08
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多