调用基本副本构造函数时收到错误 [英] I'm receiving error when calling base copy constructor

查看:54
本文介绍了调用基本副本构造函数时收到错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试显式调用基本副本ctor时,我在此代码中接收了error C2082: redefinition of formal parameter 'rval':

Im receiving error C2082: redefinition of formal parameter 'rval' in this code while trying to call base copy ctor explicitly:

 #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

Why am I asking this? according to the answers on StackOwerflow

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

I do not have to use operator :: to access base copy ctor, so why do I receive this error?

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

btw: I'm using visual studio 2010.

我还有一个问题:

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

Do I have to call base's move constructor in user defined move constructor of derived class?

推荐答案

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

To call the base constructor you need to put the call in the member initalization list

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

这篇关于调用基本副本构造函数时收到错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆