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

再次吐槽下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(18) {
    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 0;
}

 

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

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

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值