所以我有一个学校作业,要求我使用模板创建一个固定长度的字符串类,以用作更大项目的一部分,但我在开始使用固定长度的字符串时遇到了麻烦,所以我想我会来在这里寻求帮助。我对模板没有太多经验,这是导致我出现问题的原因。我当前的问题是在复制构造函数中,它给我错误,我不知道如何处理。所以这是我的类定义:
template <int T>
class FixedStr
{
public:
FixedStr ();
FixedStr (const FixedStr<T> &);
FixedStr (const string &);
~FixedStr ();
FixedStr<T> & Copy (const FixedStr<T> &);
FixedStr<T> & Copy (const string &);
private:
string Data;
};
这是给我带来问题的复制构造函数:
template <int T>
FixedStr<T>::FixedStr (const string & Str)
{
if (Str.length() == <T>)
strcpy (FixedStr<T>.Data, Str);
}
任何人都可以就如何处理这个问题给我一些建议吗?您是否看到了容易出现的错误,或者我是否以错误的方式解决了问题?感谢您能给我的任何帮助。
最佳答案
未经测试:我认为应该是
if (Str.length() == T)
Data = Str;
首先,在访问模板参数时不要使用尖括号。其次,您不对 C++ 字符串使用 strcpy
,它们支持通过赋值进行复制。
请注意,您的类中不需要自定义析构函数或复制构造函数。
字母 T
通常用于类型参数。我只会使用 Length
或 N
来代替。
这是你的类的修改版本:
#include <string>
template<int N> class FixedStr {
public:
FixedStr(const std::string&);
private:
std::string Data;
};
template<int N> FixedStr<N>::FixedStr(const std::string& Str) {
if (Str.length() == N) Data = Str;
}
int main() {
FixedStr<11> test("Hello World");
}
关于c++ - 使用模板的固定长度字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8422341/