使用模板的固定长度字符串
Fixed length string using templates
本文关键字:字符串 更新时间:2023-10-16
所以我有一项学校作业,要求我使用模板创建一个固定长度的字符串类,作为更大项目的一部分,但我在开始使用固定长度字符串时遇到了困难,所以我想来这里寻求帮助。我对模板没有太多的经验,这就是给我带来问题的原因。我目前的问题是复制构造函数,它给了我不知道如何处理的错误。下面是我的类定义:
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");
}
除非T
正在修改类型,否则不需要将其放在尖括号中。所以应该是Str.length() == T
。
不能在string
上使用strcpy
,必须使用c_str()
方法才能获得兼容的以null结尾的字符串。但这并不重要,因为无论如何都不应该使用strcpy
来分配string
对象。只需使用Data = Str
。