【发布时间】:2015-04-17 23:14:52
【问题描述】:
fndef FIXED_LENGTH_STRING_H
#define FIXED_LENGTH_STRING_H
#include <iostream>
using namespace std;
#include <string.h>
template <int Length>
class FixedLengthString
{
public:
enum Exceptions {InvalidLength};
FixedLengthString ();
FixedLengthString (const FixedLengthString <Length> &);
FixedLengthString (const char []);
~FixedLengthString ();
Copy (const FixedLengthString <Length> &);
Copy (const char []);
istream & Read ();
FixedLengthString <Length> & operator = (const FixedLengthString <Length> &);
FixedLengthString <Length> & operator = (const char []);
bool operator < (const FixedLengthString <Length> &) const;
bool operator < (const char []) const;
// also need the other comparison operators
operator const char * () const;
private:
char Data [Length + 1];
};
template <int Length>
ostream & operator << (ostream & out, const FixedLengthString <Length> & Str)
{
// display the characters in the string
return out;
}
template <int Length>
istream & operator >> (istream & in, FixedLengthString <Length> & Str)
{
Str.Read ();
return in;
}
template <int Length>
FixedLengthString <Length>::FixedLengthString (const char S [])
{
if (Length != strlen (S))
throw InvalidLength;
else
strcpy (Data, S);
}
template <int Length>
inline FixedLengthString <Length>::operator const char * () const
{
return Data;
}
#endif
编译器指向两个 Copy 构造函数。我正在创建一个以字符数作为模板参数的模板。从这里我需要一个固定长度的字符串
在我的 FixedLengthString.cpp 文件中,我有这个
FixedLengthString<Length>::Copy(const FixedLengthString <Length> & M)
{
strcpy(Data, M.Data)
}
template <int Length>
FixedLengthString<Length>::Copy(const char M [])
{
strcpy(Data, M.Data)
}
【问题讨论】:
-
我不会说这是重复的,但@Axalo 是对的;只能在头文件中定义模板。