c++ - 我们如何使用委托(delegate)构造函数从派生类调用基类构造函数

标签 c++ oop constructor-overloading inherited-constructors

我知道并且我已经阅读了很多从派生类调用基类构造函数的线程,但我想使用委托(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/

相关文章:

java - std::vector 和 java.util.Vector 之间的差异

c++ - 为什么 C++ 中的静态函数原型(prototype)参数会被 ARGS() 包围?

c++ - 无法在 Visual Studio 2019 中使用诊断工具

php - 如何检查一个类是否属于某个命名空间

java - 如何在Java中初始化嵌套的匿名数组double?

lambda - 如何在 kotlin 中重载构造函数的 lambda 返回类型不同

c++ - 将迭代器的地址传递给 STL::for_each 中的函数

oop - 如何在 UML 序列图的自消息方法中绘制方法

javascript - "this"在私有(private)函数内部调用时引用窗口

c++ - 将非 null 终止的 vector<char> 转换为字符串