私有基类构造函数仍然被调用吗? [已关闭]

问题描述 投票:0回答:2
#include <iostream>

// first base class
class Vehicle
{
public:
    Vehicle() { std::cout << "This is a Vehicle\n"; }
};

// second base class
class FourWheeler
{
public:
    FourWheeler()
    {
        std::cout << "This is a 4 wheeler Vehicle\n";
    }
};

// sub class derived from two base classes
class Car : private Vehicle, private FourWheeler
{
};

// main function
int main()
{
    // Creating object of sub class will
    // invoke the constructor of base classes?
    Car obj;
    return 0;
}

我原以为没有输出,但它给出了输出(即它运行超类的构造函数)。为什么会出现这种情况?请赐教。

c++ class inheritance constructor private-methods
2个回答
1
投票

Private用于描述类的访问控制。无论私有或公共继承,继承的类都将运行各自的构造函数。

Private 应该用于定义您不希望暴露给类外部的方法和函数的方法和函数。它并不是为了隐藏或锁定功能。


0
投票

继承中使用的 public、private 和 protected 关键字称为访问修饰符。这些更改了继承的基类成员的最大控制级别。 构造函数是不能被继承的公共方法,它们在创建对象时仅调用一次。 默认情况下,子类的构造函数会调用基类的构造函数。 如果同一个子类存在多重继承,则它们的构造函数按相同的继承顺序调用。 在你的例子中:

class Car : private Vehicle, private FourWheeler
{
    // The access modifier is private for both base classes.So, all the public and protected inherited members are treated here as private members.
    // All the private members of the base classes will not be inherited to the Car class.
    // You cannot access the inherited members outside the class or when inheriting this class.
    // The constructor of Vehicle class will be called first then FourWheeler class.
    // There is no constructor in the Car class so the compiler will generate it by default constructor.
    // It also will generate the copy constructor and other functions like assignment operator and move operator by default.

};

这里编译器会将此类代码扩展为这样。

class Car : private Vehicle, private FourWheeler
{
public:
    Car() = default; // default constructor
    Car(Car& source) = default; // copy constructor

};

构造函数将像这样扩展:

class Car : private Vehicle, private FourWheeler
{
public:
    Car(){
        //default things.
    }
};

但是基类的构造函数调用在哪里。 即使您像这样编写子类的构造函数,它也会扩展为调用所有基类的构造函数并将其默认参数传递给调用。 您的课程代码将扩展为:

class Car : private Vehicle, private FourWheeler
{
public:
    Car(): Vehicle(), FourWheeler(){
        //default things.
    }
};

“:”之后的部分称为直接初始化。直接初始化的优先级高于花括号中的部分。 那么,如果子类构造函数中有这样的语句:

class Car : private Vehicle, private FourWheeler
{
public:
    Car() : Vehicle(), FourWheeler() {
        cout << "I have created a car!\n";
    }

};

这将是输出:

This is a Vehicle
This is a 4 wheeler Vehicle
I have created a car!
© www.soinside.com 2019 - 2024. All rights reserved.