C ++构造函数的问题。这里到底要初始化什么?

问题描述 投票:0回答:1
#include<bits/stdc++.h>
using namespace std;


class Vehicle
{
private:
int speed;

public:
Vehicle(int x)
{
   speed=x;
   cout << "Vehicle's parametrized constructor called" << endl;
}
};

class Car : public Vehicle
{ 
   public:
   Car() : Vehicle(5)
   {
        cout << "Car's constructor called" << endl;
   }
};

int main()
{
    Car a;
}

输出-车辆的参数化构造函数称为汽车的构造函数称为>

由于访问说明符是公共的,因此不会继承速度。由于Car中没有速度会员,将5分配给什么?

#include 使用命名空间std; class Vehicle {private:int speed;公众:Vehicle(int x){speed = x; cout <

由于访问说明符是公共的,因此不会继承速度。

这是一种误解。派生类确实继承了基类的所有成员。访问说明符控件仅是继承的类是否可以访问成员。 Car无法直接访问speed,但成员在那。

[请记住,公共继承为“是”关系建模。 CarVehicle。如果Car没有speed成员,则不会是Vehicle

c++ inheritance constructor public
1个回答
3
投票

由于访问说明符是公共的,因此不会继承速度。

© www.soinside.com 2019 - 2024. All rights reserved.