我正在尝试制作一个程序来演示如何为我的 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/