c++ - 没有这样的运算符 "[]"匹配这些操作数

标签 c++ templates operator-overloading

我正在尝试制作一个程序来演示如何为我的 CS 类使用模板和重载运算符。这是相关代码:

主要内容:

    ArrayTemplate<int> number(0);
            number[0] = 1;
            number[1] = 2;
            number[2] = 3;

    ArrayTemplate<string> word("na");
            word[0] = "One";
            word[1] = "Two";
            word[2] = "Three";

标题:

template<class T>
T& operator [](const int index) 
{ 
    if(index >= 0 && index < ARRAY_MAX_SIZE)
        return items[index];
    else
    {
        cerr << "INDEX OUT OF BOUNDS!!!";
        exit(1);
    }
}

问题是,当我尝试使用重载的下标运算符时,我收到标题中显示的错误消息:“没有这样的运算符“[]”匹配这些操作数”我不确定为什么。它对我的整数数组和字符串数组都这样做。感谢您的帮助。

最佳答案

真的需要显示ArrayTemplate 的完整定义。

这就是您可能希望它看起来的样子:

template<class T>
class ArrayTemplate {
  public:

    // ...

    T& operator [](const int index) 
    { 
        if(index >= 0 && index < ARRAY_MAX_SIZE)
            return items[index];
        else
        {
            cerr << "INDEX OUT OF BOUNDS!!!";
            exit(1);
        }
    }

    // ...
};

请注意,operator[] 不是模板化的;只有类(class)是。

使用您当前的代码,您必须这样做:

number<int>[0] = 1;
number<int>[1] = 2;
number<int>[2] = 3;

这显然违背了您的意图。

关于c++ - 没有这样的运算符 "[]"匹配这些操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15080517/

相关文章:

c++ - 高效删除文件 Windows C++

python - 检查 PyObjects C 类型

c++ - C++ 中的模板

C++ == 运算符重载(实现)

c++ - 不工作 : override the default less-than operator of shared_ptr of a class

c++ - 匹配逻辑语句的 Rcpp 矩阵的子集

c++ - 如何在 C++ 中同时写入和读取 `fstream` 的文件?

c++ - 实例化后模板的特化?

perl - 如何覆盖 Template Toolkit 模板文件中的 WRAPPER?

c# - 为什么 C# 运算符重载必须是静态的?