我想知道为什么人们会说:
“继承类不继承构造函数”。
如果你可以使用父类的构造函数,无参构造函数无论如何都会被自动调用。
例子:
#include <iostream>
using namespace std;
class A {
private :
int x;
public :
A () {
cout << "I anyway use parameter-less constructors, they are called always" << endl;
}
A (const int& x) {
this->x = x;
cout << "I can use the parent constructor" << endl;
}
};
class B : public A {
private :
int y;
public :
B() {
}
B (const int& x, const int& y) : A (x) {
this->y = y;
}
};
int main() {
B* b = new B(1,2);
B* b1 = new B();
return 0;
}
那么‘说’正确吗,构造函数在 C++ 中是继承的?编程语言中“继承”的确切定义是什么?
提前致谢。
最佳答案
I wonder why people say: "Inheriting class doesn't inherit the constructor".
也许最好用一个例子来说明这一点:
struct Foo
{
Foo(int, int) {}
};
struct Bar : Foo
{
};
这意味着没有可以调用的 Bar::Bar(int, int)
构造函数,尽管在基类中存在具有相同参数列表的构造函数。所以你不能这样做:
Bar b(42, 42);
在 C++11 中,您实际上可以继承构造函数,但您必须对此明确:
struct Bar : Foo
{
using Foo::Foo;
};
现在,你可以说 Bar b(42, 42);
关于c++ - 我们在 C++ 中使用 "inherit"构造函数吗? "inheriting"的确切定义是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20029883/