c++ - 我们在 C++ 中使用 "inherit"构造函数吗? "inheriting"的确切定义是什么

标签 c++ inheritance constructor theory

我想知道为什么人们会说:

“继承类不继承构造函数”。

如果你可以使用父类的构造函数,无参构造函数无论如何都会被自动调用。

例子:

#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;
}

http://ideone.com/e.js/6jzkiP

那么‘说’正确吗,构造函数在 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/

相关文章:

c++ - MyClass 对象 = MyClass(); 'MyClass()' 在这里指的是一个临时对象吗?

c++ - 使用 STL 排序时比较方法问题

c++ - 从符号中删除空格

java - 如何实现父类(super class)对象转换为子类对象的效果?

C++ 文件中的最后一个字符

java - 如何将多个接口(interface)分组为一个通用的单个接口(interface)?

c++ - 如何让一组不同的子类对象共享另一组基类的一个静态变量?

r - 从两个向量(名称、值)创建命名列表

c++ - 为什么 const 成员必须在构造函数初始化器中而不是在其主体中初始化?

javascript - 是否存在 IsCallable 为假但 IsConstructor 为真的 JS 对象?