gpt4 book ai didi

c++ - 如何在派生类中声明复制构造函数,而基类中没有默认构造函数?

转载 作者:IT老高 更新时间:2023-10-28 22:35:27 24 4
gpt4 key购买 nike

请看下面的例子:

class Base
{
protected:
int m_nValue;

public:
Base(int nValue)
: m_nValue(nValue)
{
}

const char* GetName() { return "Base"; }
int GetValue() { return m_nValue; }
};

class Derived: public Base
{
public:
Derived(int nValue)
: Base(nValue)
{
}
Derived( const Base &d ){
std::cout << "copy constructor\n";
}

const char* GetName() { return "Derived"; }
int GetValueDoubled() { return m_nValue * 2; }
};

此代码不断向我抛出一个错误,即基类没有默认构造函数。当我宣布一切正常时。但是当我不这样做时,代码不起作用。

如何在派生类中声明复制构造函数而不在基类中声明默认构造函数?

感谢。

最佳答案

调用base的copy-constructor(由编译器生成):

Derived( const Derived &d ) : Base(d)
{ //^^^^^^^ change this to Derived. Your code is using Base
std::cout << "copy constructor\n";
}

理想情况下,您应该调用编译器生成的基础复制构造函数。不要考虑调用其他构造函数。我认为那是个坏主意。

关于c++ - 如何在派生类中声明复制构造函数,而基类中没有默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9309577/

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