gpt4 book ai didi

C++派生类链构造函数错误

转载 作者:太空宇宙 更新时间:2023-11-04 13:30:43 24 4
gpt4 key购买 nike

全部,

我在继承链中有 3 个类(在 C++ 中),每个类都设置了默认的基本构造函数。但是,链中的第 3 类提示第 1 类没有匹配的构造函数。下面是构造函数的代码:

class Base
{
protected:
int a, b;
public:
Base::Base(int first, int second)
{
this->a = first;
this->b = second;
}
}

class Second : protected Base
{
protected:
int c;
public:
Second::Second(int first, int second, int third = 2) : Base(first, second)
{
this->c = third;
}
}

class Final : protected Second
{
private:
int d;
public:
Final::Final(int first, int second, int third = 2) : Second(first, second, third)
{
}
}

编译时报错

“在构造函数中 Final::Final(int first, int second, int third)

没有对 Base() 的匹配调用"

为什么尝试调用 Base() 而不是 Base(first, second)?

最佳答案

这可能对您有所帮助,这就是我构建此类层次结构的方式。

class Base {
protected:
int m_a, m_b;

public:
Base( int first, int second );
virtual ~Base(){}
};

Base::Base( int first, int second ) :
m_a( first ),
m_b( second )
{}

class Second : protected Base {
protected:
int m_c;
public:
Second( int first, int second, int third = 2 );
virtual ~Second(){}
};

Second::Second( int first, int second, int third ) :
Base( first, second ),
m_c( third )
{}

class Final : protected Second {
private:
int m_d;
public:
Final( int first, int second, int third = 2 );
virtual ~Final(){}
};

Final::Final( int first, int second, int third ) :
Second( first, second, third )
{}

如果你想将你的定义保留在类中而不是在类声明之外定义它们,那么试试这个

class Base {
protected:
int m_a, m_b;

public:
Base( int first, int second ) : m_a( first ), m_b( second ) {}
virtual ~Base(){}
};

class Second : protected Base {
protected:
int m_c;
public:
Second( int first, int second, int third = 2 ) :
Base( first, second ),
m_c( third ) {}

virtual ~Second(){}
};

class Final : protected Second {
private:
int m_d;
public:
Final( int first, int second, int third = 2 ) :
Second( first, second, third ) {}

virtual ~Final(){}
};

在使用继承时,最好确保将析构函数声明为虚拟的。如果在类外部定义构造函数或函数,则只需要使用类作用域解析运算符,而要设置基本成员变量则不需要使用 this-> 指针运算符,可以像我一样使用初始化列表已在定义构造函数时显示。

关于C++派生类链构造函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31629006/

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