gpt4 book ai didi

C++ - 继承,调用哪个基本构造函数?

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:29 25 4
gpt4 key购买 nike

<分区>

我写了一个测试程序:

#include <iostream>

class base
{
public:

base()
{
std::cout << "base 1" << std::endl;
}

base(int a)
{
std::cout << "base a=" << a << std::endl;
}
};

class child : public base
{
public:

child()
{
std::cout << "child" << std::endl;
}
};

int main(int argc, char* argv[])
{

child c;

return 0;
}

程序输出如下:

$ ./a.out

base 1
child

是否有任何可能的方法将整数参数发送到基类,从而调用基类构造函数的另一种形式?

如果 base 只有一个构造函数,我会得到一个编译错误:candidate expects 1 argument, 0 provided,如您所料。但是如果我给那个构造函数一个默认参数,比如:

base(int a = 10)

然后我的程序编译并运行,输出:base a=10。 (有趣吗?)

有什么方法可以传入a的变量值吗?

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