IDE是codeblocks,源文件
第一個是頭文件time.h,定義類
// time.h
//#ifdef _TIME_H
#define _TIME_H
class Time
{
private:
int hour;
int minute;
int second;
public:
Time();
void set_time(int h, int m, int s);
void show_time();
};
//#endif
第二個是方法實現文件time_func.cpp
// time_func.cpp
#include <iostream>
#include "time.h"
Time::Time()
{
};
void Time::set_time(int h, int m, int s)
{
hour = h;
minute = m;
second = s;
return;
}
void Time::show_time()
{
std::cout << "show time: " << hour << ":"
<< minute << ":" << second << std::endl;
return;
}
第三個是main函數,main.cpp
// the main function
#include <iostream>
#include "time.h"
using namespace std;
int main()
{
Time t;
t.set_time(19, 20, 59);
t.show_time();
return 0;
}
我把條件編譯#ifdef和#endif注釋掉就能編譯通過,要不然就會出現編譯失敗:
||=== Build: Debug in test_class (compiler: GNU GCC Compiler) ===|
D:\C++\課後練習\test_class\time.h|2|error: unterminated #ifdef|
D:\C++\課後練習\test_class\main.cpp||In function 'int main()':|
D:\C++\課後練習\test_class\main.cpp|7|error: 'Time' was not declared in this scope|
D:\C++\課後練習\test_class\main.cpp|7|error: expected ';' before 't'|
D:\C++\課後練習\test_class\main.cpp|8|error: 't' was not declared in this scope|
||=== Build failed: 4 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
真心求解為何?
應該是#if**n**def和#endif吧。