C++代码常见问题解析与优化(虚函数)
代码出了什么问题?
#include <iostream>
using namespace std;
//基类,父类
class Vehicle{ //交通工具,车,抽象的概念
public:string contry;double price;Vehicle(string contry, double price){cout << "基类的构造函数被调用" << endl;this->contry = contry;this->price = price;};virtual void run(){cout << "车跑起来了" << endl;}void stop();
};//派生类,子类
class Roadster : public Vehicle{ //跑车,也是抽象,比父类感觉上范围缩小了点
public:int stateOfTop;Roadster(string contry, double price, int state) : Vehicle(contry, price){cout << "派生类的构造函数被调用" << endl;stateOfTop = state;}void openTopped();void pdrifting();
};class Bike : public Vehicle{void run() override{cout << "脚踩自行车" << endl;}};int main()
{Roadster FTYPE("法国",70,0);Bike b;return 0;
}
你的代码有几个问题,我将逐个指出并给出修改建议。
1. Vehicle
类中的 stop()
函数没有定义
你在 Vehicle
类中声明了 void stop();
,但是没有提供函数的实现(定义)。这会导致链接错误。
解决方法: 要么在类内定义它,要么至少提供一个函数体。
class Vehicle {
public:string country; // 拼写修正:contry -> countrydouble price;Vehicle(string country, double price) {cout << "基类的构造函数被调用" << endl;this->country = country;this->price = price;}virtual void run() {cout << "车跑起来了" << endl;}void stop() {cout << "车停下来了" << endl;}
};
2. Roadster
类中的 openTopped()
和 pdrifting()
函数没有定义
你声明了这两个函数,但没有提供它们的实现。
解决方法: 要么删除这些声明(如果你不打算使用),要么添加函数体。
void openTopped() {cout << "敞篷打开了" << endl;
}void pdrifting() {cout << "漂移开始了" << endl;
}
3. 拼写错误:contry
应为 country
这个是小错误,不影响编译,但会影响逻辑正确性。
4. main()
函数中创建对象后没有输出结果
虽然程序会正常执行,但为了验证构造函数是否调用了,你可以加上一些输出语句。
✅ 修改后的完整代码如下:
#include <iostream>
using namespace std;// 基类,父类
class Vehicle { // 交通工具,车,抽象的概念
public:string country;double price;Vehicle(string country, double price) {cout << "基类的构造函数被调用" << endl;this->country = country;this->price = price;}virtual void run() {cout << "车跑起来了" << endl;}void stop() {cout << "车停下来了" << endl;}
};// 派生类,子类
class Roadster : public Vehicle { // 跑车
public:int stateOfTop;Roadster(string country, double price, int state) : Vehicle(country, price) {cout << "派生类的构造函数被调用" << endl;stateOfTop = state;}void openTopped() {cout << "敞篷打开了" << endl;}void pdrifting() {cout << "漂移开始了" << endl;}
};class Bike : public Vehicle {
public:Bike(string country, double price) : Vehicle(country, price) {}void run() override {cout << "脚踩自行车" << endl;}
};int main() {Roadster FTYPE("法国", 70, 0);FTYPE.openTopped();FTYPE.pdrifting();Bike b("中国", 1.5);b.run();return 0;
}
✅ 输出示例:
基类的构造函数被调用
派生类的构造函数被调用
基类的构造函数被调用
脚踩自行车
总结:
你遇到的问题主要是以下几点:
- 成员函数只有声明没有定义(导致链接错误)。
- 拼写错误(不影响运行,但最好修正)。
- 缺少构造函数参数(对
Bike
类)。
如需进一步封装或设计更复杂的继承结构,请继续提问!