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;
}

 

上面的例子應該很明顯了,比網絡上一堆例子都簡潔明了!!!

各種怨念繼續飄過~~~~~~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM