实际开发中,类的定义保存在头文件中,比如Human.h【类的声明文件】(C++PrimerPlus)
类的成员函数的具体实现,保存在.cpp文件中,比如Human.cpp【类的方法文件】(C++PrimerPlus)
其他文件,如果需要使用这个类,就包含这个类的头文件。
具体的做法就是将下面这段内容放到.h文件里面,.h文件的命名可以使用Human.h(这里我们使用的代码是上一篇最后的那段代码)
class Human {
public:
Human();
Human(int age, int salary);
int getAge();
Human* compare1(Human* other);
private:
string name = "Unknown";
int age = 28;
int salary;
char* addr;
};
同时在头文件中需要加上一些基础的头文件和命名空间,具体如下
#pragma once
#include <string>
using namespace std;
class Human {
public:
Human();
Human(int age, int salary);
int getAge();
Human* compare1(Human* other);
private:
string name = "Unknown";
int age = 28;
int salary;
char* addr;
};
然后将类中的成员函数放在另外的.cpp文件中。命名可以使用Human.cpp。同时要在这个文件中加上刚刚写好的头文件。
具体内容如下:
#include "Human.h"
#include <iostream>
using namespace std;
Human::Human() {
name = "无名氏";
age = 18;
salary = 30000;
}
Human::Human(int age, int salary) {
cout << "调用自定义的构造函数" << endl;
this->age = age; //this是一个特殊的指针,指向这个对象本身
this->salary = salary;
name = "无名";
addr = new char[64];
strcpy_s(addr, 64, "China");
}
int Human::getAge() {
return age;
}
Human* Human::compare1(Human* other) {
if (age > other->age) {
return this; //没有创建新的对象
}
else {
return other;
}
}
然后在主函数的文件中如果需要使用Human.cpp文件中的内容,就在那个文件中添加上刚刚写好的Human的头文件即可
具体内容如下:
#include <iostream>
#include <Windows.h>
#include <string.h>
#include "Human.h"
using namespace std;
int main(void) {
Human h1(25, 30000);
Human h2(18, 8000);
Human* p;
p = &h1;
cout << p->compare1(&h2)->getAge() << endl;
system("pause");
return 0;
}
并且在前面写好的头文件和cpp文件中写过的基础头文件,在主函数的文件中不需要再写一遍了。