C++类的继承(多文件)

        网上有不少C++类继承的教程,但很多教程都是在单文件编程的场景下实现的。这篇文章会讲如何在多文件编程的场景下实现类继承。

        首先,定义一个Vehicle(机动车)类,这个类有brand(品牌)和speed(速度)两个数据属性。然后,定义Vehicle类的子类Car(汽车)类,继承Vehicle类的属性,并加入自己的ID(车牌号)属性。最后,创建一个Car实例,将brand设为Test,speed设为100,ID设为000001,并输出Car实例的属性。在现实生活中,不止是汽车,摩托车也有车牌号,而且车牌号不会那么简单,但为了方便讲解,我就这样设计这个程序。

这个程序的目录结构:

我的编程环境是Xcode,图中的c+表示源文件(.cpp),h+表示头文件(.hpp)。类定义放在头文件中,类实现和main方法放在源文件中。

程序源码:

Vehicle.hpp:

#ifndef Vehicle_hpp
#define Vehicle_hpp

#include <string>
using namespace std;
class Vehicle {
protected:
    string brand;
    double speed;
public:
    Vehicle(string newBrand, double newSpeed);
    string getBrand(void);
    double getSpeed(void);
};

#endif /* Vehicle_hpp */

Vehicle.cpp:

#include "Vehicle.hpp"
using namespace std;

Vehicle::Vehicle(string newBrand, double newSpeed) {
    this->brand = newBrand;
    this->speed = newSpeed;
}

string Vehicle::getBrand() {
    return (this->brand);
}

double Vehicle::getSpeed() {
    return (this->speed);
}

Car.hpp:

#ifndef Car_hpp
#define Car_hpp

#include "Vehicle.hpp"
using namespace std;

class Car : public Vehicle {
private:
    string ID;
public:
    Car(string newBrand, double newSpeed, string newID);
    string getID(void);
    
};

#endif /* Car_hpp */

Car.cpp:

#include "Car.hpp"

using namespace std;

Car::Car(string newBrand, double newSpeed, string newID):Vehicle(newBrand, newSpeed) {
    this->ID = newID;
}

string Car::getID() {
    return ID;
}

main.cpp:

#include <iostream>
#include "Car.hpp"
int main(int argc, const char * argv[]) {
    
    Car * car1 = new Car("Test", 100, "000001");
    cout << "Car 1:" << endl;
    cout << "Brand: " << car1->getBrand() << endl;
    cout << "Speed: " << car1->getSpeed() << endl;
    cout << "ID: " << car1->getID() << endl;
    return 0;
}

        这个程序的重点是Car类的构造函数。Car类是Vehicle类的子类,在类定义中声明Car类的构造函数时,不加“:Vehicle(newBrand, newSpeed)”,但在源文件中实现构造函数时,要加上“:Vehicle(newBrand, newSpeed)”,以调用父类的构造函数。

程序运行结果:

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qifeng_xiaozi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值