具体区别如下:
结构体 -> 结构体变量
{
结构体:struct student{ 具体是多少,年龄,名字,性别,成绩 }
结构体变量: stu{ 名字:张三,年龄:18,成绩:96 }
}
类 ->对象 (类是对象的模板 ,对象是类的实例化)
class student
{
年龄,名字,性别,成绩
}
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>using namespace std;class Car{
public: //公共权限string color;string brand;string type;int year;void (*printfCarInfo)(string color,string brand,string type,int year);void (*carRun)(string type); //函数指针,执行车运行的函数void (*carStop)(string type); //函数指针,执行车停止的函数
};void bmwThreePrintfInfo(string color,string brand,string type,int year)
{string str = "车的品牌是:"+brand+",型号是:"+type+",颜色是:"+color+"上市年限是:" + std::to_string(year);cout << str <<endl;
}void AodiA6PrintfInfo(string color,string brand,string type,int year)
{string str = "车的品牌是:"+brand+",型号是:"+type+",颜色是:"+color+"上市年限是:" + std::to_string(year);cout << str <<endl;}int main()
{Car BMWthree;BMWthree.color = "白色";BMWthree.brand = "宝马";BMWthree.type = "3系";BMWthree.year = 2023;BMWthree.printfCarInfo = bmwThreePrintfInfo; //函数指针指向具体的函数的时候BMWthree.printfCarInfo(BMWthree.color,BMWthree.brand,BMWthree.type,BMWthree.year);Car *AodiA6 = new Car();//AodiA6 = (struct Car*)malloc(sizeof (struct Car));AodiA6 ->type = "A6";AodiA6 ->year = 2018;AodiA6 ->brand = "奥迪";AodiA6 ->color = "黑色";AodiA6 ->printfCarInfo = AodiA6PrintfInfo;AodiA6 ->printfCarInfo(AodiA6 ->color,AodiA6 ->brand,AodiA6 ->type,AodiA6 ->year);return 0;
}
以上的代码在C++中:
1.char * 类型会报错,应当改成 string ,包含头文件string.h
2.printf打印不成功,所以换成字符串,cout出来
string str = "车的品牌是:"+brand+",型号是:"+type+",颜色是:"+color+"上市年限是:" + std::to_string(year);
std::to_string()这个函数将整型数转换为字符串
3.,使用malloc在堆申请结构体空间有问题,所以直接在此引入类的概念:struct结构体,在写结构体指针struct Car *AodiA6 的时候,打印不出结果;
应当把结构体改成类:class,其中涉及权限问题,应当加上public:
4.