【发布时间】:2021-02-21 19:15:38
【问题描述】:
我有以下代码:
#include <iostream>
using namespace std;
class Base {
protected:
char const* name;
public:
Base(char const* n) : name{n} {
cout << "Base constructed" << endl;
}
};
class Color : virtual public Base {
protected:
Color(char const* n) : Base(n) {
cout << "Color constructed" << endl;
}
};
class Text : public virtual Base {
protected:
Text(char const* n) : Base(n) {
cout << "text constructed" << endl;
}
};
class NexButton : public Color , public Text {
public:
NexButton(char const* n) : Base(n), Color(n), Text(n) {
cout << "NexButton constructed" << endl;
}
};
int main() {
NexButton btn{"b0"};
}
哪些输出:
Base constructed
Color constructed
text constructed
NexButton constructed
但是下面的代码:
#include <iostream>
using namespace std;
class Base {
protected:
char const* name;
public:
Base(char const* n) : name{n} {
cout << "Base constructed" << endl;
}
};
class Color : virtual public Base {
using Base::Base;
};
class Text : public virtual Base {
using Base::Base;
};
class NexButton : public Color , public Text {
using Color::Color;
using Text::Text;
};
int main() {
NexButton btn{"b0"};
}
输出:
Base constructed
不明白为什么第二个代码sn-p只输出BaseConstructed;派生类不应该向终端输出一些东西吗?因为他们正在继承构造函数?除了派生类输出到 cout 之外,这两个代码 sn-ps 在很多方面都不是相同的吗? (不相同)
视觉上,为什么没有输出:
Base constructed
Base constructed
Base constructed
Base constructed
【问题讨论】:
-
“派生类不应该也向终端输出一些东西吗?” 不,它不会输出任何东西,除非你告诉它这样做,而不是使用编译器生成的构造函数。
-
您没有为派生类指定构造函数。您的 4 个 c'tors 仍在被调用,但您的类的“隐式定义的默认构造函数”不打印任何内容。
-
使用不同于调用。 using 引入构造函数,就好像它们是你自己的一样。您只能以这种方式调用您自己的构造函数之一。但是,没有什么可以阻止您创建自己的构造函数来完全满足您的需求(例如调用或不调用您想要的构造函数)
-
为什么会调用“隐式定义的默认构造函数”?我正在为构造函数提供一个参数。
-
@N.Prone:如果我是 OP,我不会理解你的评论。请将其扩展为一个答案,准确解释隐式定义了哪些构造函数以及原因。
标签: c++ inheritance using