gpt4 book ai didi

c++ - C++可以初始化基类的基类吗?

转载 作者:行者123 更新时间:2023-12-01 14:13:01 25 4
gpt4 key购买 nike

我正在尝试以下代码段,

#include <string>

class A {
protected:
std::string name;
public:
A(std::string name):name(){}
};

class B: public A {
public:
B() : A("B") {}
};

class C: public B {
public:
C(): A("C"){} //<-- this is not allowed, but I want to make C has its own name
};
显然,这是不允许的,实现此目标的最佳方法是什么?

最佳答案

重写B的构造函数

B(const std::string& name = "B") : A(name) {}
是一种方式。在这里,我为其配备了默认值,因此它仍然充当默认构造函数。

关于c++ - C++可以初始化基类的基类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63704567/

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