c++中兩個頭文件定義同名類的解決辦法


今天考慮了一個問題,如果兩個頭文件比如time.h times.h里面都定義了一個time的類,要怎么解決?vs編譯器只對cpp文件進行編譯,在編譯階段,這兩個頭文件的實現文件都不會出錯,如果不在主函數中用到time這個類,程序也不會有問題。但是如果用到,那就是disaster!!!,如果你不得不在兩個頭文件中定義同名類,下面是我自己思考出來的最簡單的解決方式---》》用不同的作用域包含

#ifndef TIME_H
#define TIME_H
namespace time1
{
    class Time
    {
    public:
        Time(int hour, int minute, int second);
        Time();
        void tick();
        void show();
    private:
        int hour;
        int minute;
        int second;
    };
}

#endif
#include "Time.h"
#include <iostream>
#include <iomanip>

using namespace std;
time1::Time::Time(int hour, int minute, int second)   //必須第一個是作用域
{
    this->minute = minute;
    this->hour = hour;
    this->second = second;
}

time1::Time::Time()  
{
    this->minute = 0;
    this->hour = 0;
    this->second = 0;
}

void time1::Time::tick()
{
    ++second;
}

void time1::Time::show()
{
    cout << setw(2) << setfill('0') << hour << "" << setw(2) << minute << "" << setw(2) << second << "" << endl;
}
#ifndef TIMES_H
#define TIMES_H
namespace time2
{
    class Time
    {
    public:
    protected:
    private:
    };
}


#endif

這里沒寫我的times.h的cpp文件為空,實現與否都一個樣

主函數,這樣可以順利運行處結果,如果不用作用域包含,則會出現重復定義的后果

#include "Times.h"
#include "Time.h"
int main()
{
    time1::Time  t2(16,44,10);
    time1::Time  t1;
    t1.show();
    t1.tick();
    t1.show();
    t2.show();
    return 0;
}

 


免責聲明!

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



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