今天考慮了一個問題,如果兩個頭文件比如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; }