头文件中写类的声明、结构的声明、函数原型、宏定义等
注意不可以定义全局变量,否则可能会引起重复定义的错误
#pragma once
#define MAXPRICE 200000
//结构体定义,这个地方一定要加typedef(否则vs2019会报重复定义的错)
typedef struct Book {
char Name[50];
int ID;
double price;
}book;
//车辆类定义
class Vehicle {
public:
char Brand[50];
double price;
int siteNum;
Vehicle(void) {
price = 0;
siteNum = 0;
strcpy_s(Brand, "car");
}
Vehicle(char* id, double newprice, int sitenum) {
strcpy_s(Brand, id);//char*转char[]拷贝 char[]转char*直接赋值
price = newprice;
siteNum = sitenum;
}
public:
void printVehicleInfo();
};
//结构体作为参数
void printDetail(Book book);
//结构体指针作为参数
void printDetail(Book* book);
//对象指针作为参数
void printCarInfo(Vehicle* vehicle);
//对象引用作为参数
void printCarInfo(Vehicle& vehicle);
//复制信息,对象引用作为参数,返回引用
Vehicle* copyCarInfo(Vehicle& vehicle);
源文件中主要是对.h文件中声明的定义、实现,注意引入“testStruct.h”
testStruct.cpp
#include
#include
#include "testStruct.h"
using namespace std;
//输出详细信息
void printDetail(Book book) {
cout << "书名:" << book.Name << endl;
cout << "ID:" << book.ID << endl;
cout << "价格:" << book.price << endl;
}
void printDetail(Book* book) {
cout << endl;
cout << "指针作为参数:" << endl;
cout << "书名:" << book->Name << endl;
cout << "ID:" << book->ID << endl;
cout << "价格:" << book->price << endl;
}
void Vehicle::printVehicleInfo() {//this是个指针
cout << "品牌:" << this->Brand << endl;
cout << "价格:" << this->price << endl;
cout << "承载人数:" << this->siteNum << endl;
}
void printCarInfo(Vehicle* vehicle) {
cout << "品牌:" << vehicle->Brand << endl;
cout << "价格:" << vehicle->price << endl;
cout << "承载人数:" << vehicle->siteNum << endl;
}
void printCarInfo(Vehicle& vehicle) {
cout << "品牌:" << vehicle.Brand << endl;
cout << "价格:" << vehicle.price << endl;
cout << "承载人数:" << vehicle.siteNum << endl;
}
Vehicle* copyCarInfo(Vehicle& vehicle) {
Vehicle* pnewvehicle = &vehicle;
strcpy_s(vehicle.Brand, "MINI-point");
vehicle.price = 200000;
return pnewvehicle;
}
在其他文件(例如含有main()入口的testNew.cpp)中使用testStruct定义的函数,只需要引入testStruct.h即可
testNew.cpp
#include
#include
#include "testStruct.h"
using namespace std;
int main(){
Vehicle myminicar;
Vehicle* minicarinfo = copyCarInfo(myminicar);
printCarInfo(minicarinfo);
cout << "------------分割线------------" << endl;
cout << "设置的宏定义MAXPRICE:" <<MAXPRICE << endl;
}
执行结果

在cpp文件中结构体可以不使用typedef,可以直接定义,但是在头文件中不加typedef会出现报错
