Re: [問題] A類別的函式內 呼叫 A類別函式 出錯

作者: Caesar08 (Caesar)   2016-06-02 15:52:00
class A;
這是class declaration
template<class>class B;
這也是class declaration
class C
{
int i;
public:
void test();
};
這是class definition
其中void test()是member function declaration
template<class T>
class D
{
T i;
public:
void test();
};
這也是class definition
其中void test()也是member function declaration
void C::test(){}
這是member function definition
template<class T>
void D<T>::test(){}
這也是member function definition
非class template的class(如A與C)
會將member function的declaration與definition分開
declaration放在.h
definition放在.cpp
而class template的class(如B與D)
有2種做法(第3種是export,但把這東西忘了吧)
一種是把member function的declaration與definition放在一起
例如
//.hpp or .hxx or anything but not .h
template<class T>
class E
{
T i;
public:
void test(){}
};
然後為了說明這不是一般的.h檔案,所以會把這檔案取成別的名字
常見的有.hpp或.hxx或乾脆沒有副檔名(如iostream)
所以這時候,就不需再有一個.cpp檔案了
另一種做法是按照傳統,把member function的declaration與definition分開
但是在.h檔案(或.hpp或其他的)裡面include該member function definition的檔案
例如
//.h
template<class T>
class F
{
T i;
public:
void test();
};
#include"your/member/function/definition/file.cpp"
//.cpp
template<class T>
void F<T>::test(){}
然而你的方法卻是include .cpp(然後裡面在include .h)
不是不能這麼做
只是當別人要用你的檔案時,他會以為只要include .h就好
然後就發現compile不過,之後才知道原來你用的方式跟別人不一樣
我以前都用第二種做法,但後來發現用第一種做法比較好
(用第二種容易讓別人搞混,以為compile時也要把.cpp放進去,結果就error了)
還有,你給的那連結,我看一眼就關掉了
連main function都寫不好的網誌,沒有看的必要
作者: hunandy14 (Charlott.HonG)   2016-06-02 17:08:00
受益良多,一直想問這些問題,又不知道怎麼問我試著練習一下檔案在,差不多就是樣子嗎無副檔名寫在一起 https://goo.gl/xoQ4Xw分開寫在.cpp https://goo.gl/7fch9z想再問的,我如果寫在同一個檔案 定義跟宣告 要分開嗎你說[main function都寫不好] 具體是什麼意思呢想知道~還有一個奇怪的問題XD 為什麼要把.h分開呢 直接引.cpp
作者: bibo9901 (function(){})()   2016-06-02 17:22:00
在同一個檔案裡可分可不分 看你的需要分開純粹是一個檔案太多行了不好看 #include其實就是複製貼上 和你寫在同一個檔案一樣意思
作者: EdisonX (卡卡獸)   2016-06-02 19:47:00
受教了 推一個。

Links booklink

Contact Us: admin [ a t ] ucptt.com