C++ 类的头文件、实现、使用

时间:2023-01-30 17:13:35

再次吐槽下C++Primer这本书,啰哩啰嗦,废话太多。如果我来翻译的话,绝对删减一堆没用的---仅限于发牢骚。

不知道是否经典的做法

类中的成员声明在头文件中,定义(我更喜欢叫实现)在源文件中,使用的时候导入头文件即可。

但是,这里没有说明的是,源文件中需要导入头文件,而头文件不需要导入源文件!!!

至于为什么这样的导入能够成功执行,我猜应该是编译器的功劳了--但是书上没有说明。

代码如下:

// Person类的头文件,声明类的各成员
#ifndef PERSON_H
#define PERSON_H #include <iostream>
#include <string> using namespace std; // 这个不建议 class Person {
private:
string name;
int age; public:
Person();
Person(const string &_name);
Person(const string &_name, const int &_age); public:
~Person();
}; #endif // PERSON_H
// Person类的源文件,bt啊
#include "person.h" using namespace std; // 这个不建议 Person::Person() : name("anonymous"), age() {
cout << "default constructor called" << endl;
}
Person::Person(const string &_name) : name(_name) {
cout << "Person(const string&) constructor called" << endl;
}
Person::Person(const string &_name, const int &_age) : name(_name), age(_age) {
cout << "Person(const string&, const int&) constructor called" << endl;
}
Person::~Person() {
cout << "before default destructor" << endl;
}
// Person类的使用!!!
#include "person.h"
#include <iostream> using namespace std; int main(int argc, char *argv[]) {
{ Person person; } cout << "Hello World!" << endl;
return ;
}

上面的例子应该很明显了,比网络上一堆例子都简洁明了!!!

各种怨念继续飘过~~~~~~