SAR*_*SAR 1 c++ operator-overloading
我想重载operator []来接受2 int,以便用户可以指定如下范围的索引:
MyClass[1:5]
Run Code Online (Sandbox Code Playgroud)
我尝试了这个:
void operator[](const int, const int);
Run Code Online (Sandbox Code Playgroud)
希望我可以用逗号使用它:
MyClass[1,5]
Run Code Online (Sandbox Code Playgroud)
但出现编译器错误:
too many parameters for this operator function
Run Code Online (Sandbox Code Playgroud)
有没有办法可以实现这种行为?
谢谢
编辑:我希望操作员会做这样的事情:
struct MyClass
{
vector<std::string> data;
void operator[] (const int start, const int end)
{
for(int index = start; index <= end; index++)
{
cout << data[index] << '\n';
}
}
};
Run Code Online (Sandbox Code Playgroud)
不可能。
您需要选择其他语法,例如:
MyClass(1,5)-超载operator()。MyClass.foo(1,5) -成员函数。MyClass[{1,5}]-重载operator[]了类类型的参数,该参数具有一个接受2个参数的构造函数。