zoukankan      html  css  js  c++  java
  • 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;
    }

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

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

  • 相关阅读:
    plsql-游标
    pl/sql--基本的语法及操作
    Oracle数据库管理
    JMS-ActiveMq-订阅发布模式
    JMS-ActiveMq-点对点模式
    JMS-ActiveMq
    poi之excel的模板导入(随后分享)
    数据流写出util
    dba_tables、all_tables、user_tables
    oracle的一些操作
  • 原文地址:https://www.cnblogs.com/larryzeal/p/5620470.html
Copyright © 2011-2022 走看看