再次吐槽下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;
}

 

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

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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-11
  • 2021-07-29
  • 2022-01-29
  • 2022-12-23
  • 2022-02-05
  • 2021-12-01
猜你喜欢
  • 2021-05-18
  • 2021-12-13
  • 2022-12-23
  • 2022-12-23
  • 2021-12-04
  • 2022-03-04
  • 2021-08-02
相关资源
相似解决方案