以前寫代碼的時(shí)候就遇到VC++對(duì)友元支持得不太好的問(wèn)題,同時(shí)也看過(guò)侯捷老師對(duì)gnu c++, VC++, BCB 三種編譯器的比較,其中VC++對(duì)模板友元的支持就不是很好。
今天晚上寫了一個(gè)比較簡(jiǎn)單的鏈表的模板類,其中頭文件Chain.h原來(lái)的代碼如下:
#include <iostream>
using namespace std;
#ifndef _CHAIN
#define _CHAIN
template<class T>
class?ChainNode
{
?friend class Chain<T>;
private:
?T data;
?ChainNode<T> *link;
};
template<class T>
class Chain{
public:
?Chain()
?{
??first = 0;
?};
?~Chain();
?bool IsEmpty() const {return first == 0;}
?int Length() const;
?bool Find(int k, T& x) const;
?int Search(const T& x) const;
?//Chain<T>& Delete(int k, T& x);
?Chain<T>& Insert(int k, const T& x);
?void Output(ostream& out = cout) const;
private:
?ChainNode<T> *first; // 指向第一個(gè)節(jié)點(diǎn)的指針
};
#endif? // _CHAIN
結(jié)果報(bào)錯(cuò):
--------------------Configuration: Chain - Win32 Debug--------------------
Compiling...
Chain.cpp
g:\work plan\c++ code practice\chain\chain.h(17) : error C2059: syntax error : '<'
??????? g:\work plan\c++ code practice\chain\chain.h(21) : see reference to class template instantiation 'ChainNode<T>' being compiled
g:\work plan\c++ code practice\chain\chain.h(17) : error C2238: unexpected token(s) preceding ';'
??????? g:\work plan\c++ code practice\chain\chain.h(21) : see reference to class template instantiation 'ChainNode<T>' being compiled
g:\work plan\c++ code practice\chain\chain.h(40) : error C2989: 'Chain' : template class has already been defined as a non-template class
??????? g:\work plan\c++ code practice\chain\chain.h(17) : see declaration of 'Chain'
g:\work plan\c++ code practice\chain\chain.cpp(6) : error C2059: syntax error : '<'
g:\work plan\c++ code practice\chain\chain.cpp(6) : error C2588: '::~Chain' : illegal global destructor
g:\work plan\c++ code practice\chain\chain.cpp(6) : fatal error C1903: unable to recover from previous error(s); stopping compilation
Error executing cl.exe.
Chain.obj - 6 error(s), 0 warning(s)
感覺從代碼來(lái)看應(yīng)該是沒有問(wèn)題的,如果哪個(gè)高手看出問(wèn)題來(lái)了請(qǐng)一定告訴我啊,如果知道編譯不通過(guò)的原因也請(qǐng)一定要告訴我啊。沒辦法,最后采用解決的辦法就是修改ChainNode的定義了,定義為結(jié)構(gòu)體:)
template<class T>
struct ChainNode
{
? T data;
? ChainNode<T> *link;
};
反正結(jié)構(gòu)體中的數(shù)據(jù)成員都是public的,至于訪問(wèn)限制的實(shí)現(xiàn)就依靠迭代器來(lái)實(shí)現(xiàn)了,g++的STL中的樹結(jié)點(diǎn)不也是結(jié)構(gòu)體嗎?:)
posted on 2006-06-17 23:39
Bourne 閱讀(2643)
評(píng)論(4) 編輯 收藏 引用