我知道并且我已经阅读了很多从派生类调用基类构造函数的线程,但我想使用委托(delegate)构造函数来实现它
这是我的代码
错误状态
“委托(delegate)构造函数不能有其他内存初始化器”
#include <iostream>
using namespace std;
// Shivang101
class Base
{
private:
int value;
public:
Base() : value{0}
{
cout << "Base no args constructor called" << endl;
}
Base(int x) : value{x}
{
cout << "Base (int) overloaded constructor called" << endl;
}
~Base()
{
cout << "Base Destructor called" << endl;
}
};
class Derived : public Base
{
private:
int testing_value;
int doubled_value;
// using Base ::Base;
public:
Derived() : Derived{0, 0}
{
cout << "NO arg constructor called" << endl;
};
// In the below line I'm Trying a call the base class constructor but getting error
Derived(int testing_val) : Base{testing_val}, Derived{testing_val, 0}
{
cout << "One arg constructor called" << endl;
}
Derived(int testing_val, int doubled_val) : testing_value{testing_val}, doubled_value{doubled_val}
{
cout << "Delegating constructor/ overloaded called" << endl;
}
~Derived()
{
cout << "Derived destructor called" << endl;
}
};
int main()
{
Derived d{1000};
return 0;
}
我想调用我的基类构造函数并将Base类中的“值”初始化为“1000”,并初始化中的“testing_*value”和“doubled_*value”派生类分别为“1000”和“2000”
最佳答案
构造函数负责初始化所有成员和基本子对象。
委托(delegate)构造函数委托(delegate)给不同的构造函数。
不可能两者兼而有之。要么委托(delegate)其他地方,要么初始化成员和基础子对象。
引用自cppreference :
Delegating constructor
If the name of the class itself appears as class-or-identifier in the member initializer list, then the list must consist of that one member initializer only; such a constructor is known as the delegating constructor, and the constructor selected by the only member of the initializer list is the target constructor
我想你可以重新排列构造函数以达到预期的效果。虽然我不知道如何在不实现另一个构造函数或更改委托(delegate)方式的情况下完成此操作,因为目前采用两个参数的构造函数调用 Base
的默认构造函数,但委托(delegate)给它的构造函数尝试调用Base{testing_val}<
。
关于c++ - 我们如何使用委托(delegate)构造函数从派生类调用基类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75396996/