网上有不少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)”,以调用父类的构造函数。
程序运行结果: