class warrior { private: int strength; int num; string name; public: warrior(int i,string name_temp,int n) { strength = i; bnum = 0; rnum = 0; num = n; name = name_temp; } ~warrior(){} string get_name() { return name; } int get_strength() { return strength; } int get_num() { return num; } };分别存放到头文件和源文件
时间: 2024-01-17 19:03:40 浏览: 86
将类定义放入头文件 `warrior.h` 中:
```c++
#ifndef WARRIOR_H
#define WARRIOR_H
#include <string>
class warrior {
private:
int strength;
int num;
std::string name;
public:
warrior(int i, std::string name_temp, int n);
~warrior();
std::string get_name();
int get_strength();
int get_num();
};
#endif // WARRIOR_H
```
将类的实现放入源文件 `warrior.cpp` 中:
```c++
#include "warrior.h"
warrior::warrior(int i, std::string name_temp, int n) {
strength = i;
num = n;
name = name_temp;
}
warrior::~warrior() {}
std::string warrior::get_name() {
return name;
}
int warrior::get_strength() {
return strength;
}
int warrior::get_num() {
return num;
}
```
在使用该类的代码中,只需要包含头文件 `warrior.h` 即可,如:
```c++
#include "warrior.h"
int main() {
warrior w(10, "Tom", 1);
std::string name = w.get_name();
int strength = w.get_strength();
int num = w.get_num();
return 0;
}
```
阅读全文
相关推荐


















