类的形式和结构体的形式
其主要目的是将数据和与数据相关的操 作封装在一起。例如,如果你有一个“汽车”类,它可能包含颜色、品牌、型号等属性(数据成员),以及 启动、停止、加速等行为(成员函数)。每当你基于这个类创建一个对象时,你就有了一个具体的汽 车,具有这些属性和行为。
结构体
struct Car{ //汽车“类”
char *color; //颜色
char *brand; //品牌
char *type; //车型
int year; //年限
void (*printCarInfo)(char *color,char *brand,char *type, int year); //函数指针,指向车介绍函数
void (*carRun)(char *type); //函数指针,指向车运行的函数
void (*carStop)(char *type); //函数指针,执行车停止的函数
};
类:
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); //函数指针,执行车停止的函数
};
类和结构体相比:
c++中的字符串使用 string
1、区别类里面的成员的 :(默认是私有的(private))
2、如果是变量的类型是指针,开辟空间的时候不用malloc 而是用new()
在一个类中的成员函数可以直接使用该同类中成员数据。
成员函数的定义
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 realprintf();
};
void Car::realprintf(){
string str = "车的品牌是:" + brand
+ ",型号是: " + type
+ ",颜色是:" + color
+ ",上市年限是:" + std::to_string(year);
cout << str << endl;
}
组合
在 C++中,一个类包含另一个类的对象称为组合(Composition)。这是一种常见的设计模式,用 于表示一个类是由另一个类的对象组成的。这种关系通常表示一种"拥有"("has-a")的关系。
class Wheel{
public:
string brand;
int year;
void wheelPrintInfo();
};
Wheel::wheelPrintInfo(){
cout << "我的轮胎品牌是:" << brand << endl;
cout << "我的轮胎日期是:" << year << endl;
}
class Car{ //汽车“类”
public:
string color; //颜色
string brand; //品牌
string type; //车型
int year; //年限
Wheel w1;
void (*printCarInfo)(string color,string brand,string type, int year); //函数
指针,指向车介绍函数
void (*carRun)(string type); //函数指针,指向车运行的函数
void (*carStop)(string type); //函数指针,执行车停止的函数
void realprintf();
};
void Car::realprintf(){
string str = "车的品牌是:" + brand
+ ",型号是: " + type
+ ",颜色是:" + color
+ ",上市年限是:" + std::to_string(year);
cout << str << endl;
}
这时候car类的变量就可以调用Wheel的成员。