[問題] 將 class declaration 和 definition 分開的問題
小弟是 C++ 初學者, 之前都是用 C 在寫 code
最近為了熟悉物件導向, 自己看書在學 C++
剛看到有一個章節是談到把 class 的宣告和定義分開
於是我就馬上寫了一個簡單的 class 來測試
但卻發生問題無法成功 compile
看錯誤訊息也看不出來是哪邊有問題
想請問比較有經驗的大大是哪個步驟有做錯
我的測試步驟如下:
1. 撰寫檔案 MyClass.h, 內容如下:
class MyClass{
public:
void displayMsg();
};
2. 撰寫檔案 MyClass.cpp, 內容如下:
#include <iostream>
using std::cout;
#include "MyClass.h"
void MyClass::displayMsg(){
cout << "My first class\n";
}
3. 撰寫檔案 test.cpp, 內容如下:
#include "MyClass.h"
int main(){
MyClass obj1;
obj1.displayMsg();
}
我照書上的步驟寫了這三個檔案, 並嘗試將 MyClass.cpp 和 test.cpp compile
但 compile 這兩個檔案時都得到一樣的錯誤訊息
-[Linker error] undefined reference to 'MyClass::displayMsg()'
但這三個檔案內容我幾乎是完全照著書上打下來的
想請問編寫 c++ 有經驗的大大
我是哪個步驟出了問題@@?
謝謝 Orz
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 122.118.36.38
推
08/29 17:46, , 1F
08/29 17:46, 1F
→
08/29 17:46, , 2F
08/29 17:46, 2F
→
08/29 17:47, , 3F
08/29 17:47, 3F
→
08/29 17:47, , 4F
08/29 17:47, 4F
→
08/29 17:48, , 5F
08/29 17:48, 5F
→
08/29 17:49, , 6F
08/29 17:49, 6F
→
08/29 17:49, , 7F
08/29 17:49, 7F
→
08/29 17:51, , 8F
08/29 17:51, 8F
→
08/29 17:51, , 9F
08/29 17:51, 9F
→
08/29 17:52, , 10F
08/29 17:52, 10F
→
08/29 17:53, , 11F
08/29 17:53, 11F
推
08/29 17:53, , 12F
08/29 17:53, 12F
→
08/29 17:53, , 13F
08/29 17:53, 13F
→
08/29 17:54, , 14F
08/29 17:54, 14F
→
08/29 18:23, , 15F
08/29 18:23, 15F
推
08/29 18:40, , 16F
08/29 18:40, 16F
→
08/29 19:11, , 17F
08/29 19:11, 17F
→
08/30 00:33, , 18F
08/30 00:33, 18F
推
08/30 00:34, , 19F
08/30 00:34, 19F
推
06/26 00:15, , 20F
06/26 00:15, 20F