#include <stdio.h> // 包含标准输入输出库
#include <stdlib.h> // 包含通用工具库(如malloc, free等)
#include <string> // 包含C++ string类定义
#include <iostream> // 包含C++输入输出流库
using namespace std; // 使用std命名空间,避免每次调用标准库函数时都需要加上前缀std::
// 定义一个汽车结构体,用于表示汽车的基本信息
struct Car{
string color; // 颜色
string brand; // 品牌
string type; // 车型
int year; // 年限
// 函数指针,指向打印汽车信息的函数
void (*printCarInfo)(string color,string brand,string type, int year);
// 函数指针,指向车运行的函数
void (*carRun)(string type);
// 函数指针,执行车停止的函数
void (*carStop)(string type);
};
// 定义一个汽车类,与上述结构体类似,但使用了类的方式,并且添加了一个成员函数realPrintCarInfo
class car{
public:
string color; // 颜色
string brand; // 品牌
string type; // 车型
int year; // 年限
// 函数指针,指向打印汽车信息的函数
void (*printCarInfo)(string color, string brand, string type, int year);
// 函数指针,指向车运行的函数
void (*carRun)(string type);
// 函数指针,执行车停止的函数
void (*carStop)(string type);
// 成员函数,用于打印汽车信息
void realPrintCarInfo();
};
// 实现realPrintCarInfo成员函数,该函数以更直观的方式打印汽车信息
void car::realPrintCarInfo(){
cout << "成员函数打印" << endl;
string str = "车的品牌是:" + brand
+ ",型号是: " + type
+ ",颜色是:" + color
+ ",上市年限是:" + std::to_string(year);
cout << str << endl;
}
// 定义一个打印宝马3系汽车信息的函数
void bwmThreePrintCarInfo(string color,string brand,string type, int year)
{
printf("车的品牌是:%s, 型号是: %s, 颜色是:%s,上市年限是%d\n",brand.c_str(), type.c_str(), color.c_str(), year);
}
// 定义一个打印奥迪A6汽车信息的函数
void A6PrintCarInfo(string color,string brand,string type, int year)
{
printf("车的品牌是:%s,型号是: %s, 颜色是:%s, 上市年限是%d\n",brand.c_str(), type.c_str(), color.c_str(), year);
}
int main()
{
// 创建一个结构体变量BWMthree并初始化其属性值
struct Car BWMthree;
BWMthree.color = "白色";
BWMthree.brand = "宝马";
BWMthree.type = "3系";
BWMthree.year = 2023;
BWMthree.printCarInfo = bwmThreePrintCarInfo;
// 调用BWMthree的printCarInfo函数打印信息
BWMthree.printCarInfo(BWMthree.color, BWMthree.brand, BWMthree.type, BWMthree.year);
// 动态创建一个car类的对象AodiA6,并初始化其属性值
car *AodiA6 = new car();
AodiA6->color = "黑色";
AodiA6->brand = "奥迪";
AodiA6->type = "A6";
AodiA6->year = 2008;
AodiA6->printCarInfo = A6PrintCarInfo;
// 调用AodiA6的printCarInfo函数打印信息
AodiA6->printCarInfo(AodiA6->color,AodiA6->brand,AodiA6->type,AodiA6->year);
// 释放动态分配的内存
delete AodiA6;
return 0;
}
此代码示例展示了如何通过结构体和类来描述对象(这里是以汽车为例),以及如何利用函数指针实现对不同对象类型的不同行为。同时,也演示了C++中成员函数的定义与使用方法。