gpt4 book ai didi

c++ - 调用基本复制构造函数时收到错误

转载 作者:行者123 更新时间:2023-11-30 03:04:10 24 4
gpt4 key购买 nike

我收到 error C2082: redefinition of formal parameter 'rval' 在尝试显式调用基本复制 ctor 时:

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

那就OK了。

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

我不必使用运算符 :: 来访问基本复制构造函数,那么为什么我会收到此错误?

顺便说一句:我正在使用 visual studio 2010。

我还有一个问题:

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

最佳答案

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

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

关于c++ - 调用基本复制构造函数时收到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8888101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com