c++ - 使用模板的固定长度字符串

标签 c++

所以我有一个学校作业,要求我使用模板创建一个固定长度的字符串类,以用作更大项目的一部分,但我在开始使用固定长度的字符串时遇到了麻烦,所以我想我会来在这里寻求帮助。我对模板没有太多经验,这是导致我出现问题的原因。我当前的问题是在复制构造函数中,它给我错误,我不知道如何处理。所以这是我的类定义:

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 通常用于类型参数。我只会使用 LengthN 来代替。

这是你的类的修改版本:

#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/

相关文章:

c++ - 将派生类型转换为基类型

c++ - Windows 应用程序以非管理员身份运行时看到文件的旧版本而不是当前版本

c++ - 在 C++ 中删除指针数组时析构函数崩溃

c++ - 是否有内置深层复制功能的作用域指针?

c++ - 手动设置 Visual Studio 2012 的 C++ 语言版本

c++ - 为什么进程会在 RtlExitUserProcess/LdrpDrainWorkQueue 中挂起?

c++ - 使用两个对象作为 unordered_map 或替代方案的哈希键

c++ - 为什么 putchar ('\\\' );不会工作

c++ - 为什么当 cout 显示正确大小时 printf 显示 vector 大小为 0?

c++ - 面向 MATLAB 用户的调试编译语言简介