C++ 如何在C+中重载索引运算符+;?
下面的代码声明了一个重载C++ 如何在C+中重载索引运算符+;?,c++,operator-overloading,C++,Operator Overloading,下面的代码声明了一个重载操作符[]的类,如下所示: #include <iostream> #include <vector> using namespace std; class BitSet { private: int size; public: vector<int> set; int &operator [] (int index) { return set[index]; } Bi
操作符[]
的类,如下所示:
#include <iostream>
#include <vector>
using namespace std;
class BitSet
{
private:
int size;
public:
vector<int> set;
int &operator [] (int index) {
return set[index];
}
BitSet(int nsize = 0)
{
cout << "BitSet creating..." << endl;
size = nsize;
initSet(size);
}
void initSet(int nsize)
{
for (int i = 0; i < nsize; i++)
{
set.push_back(0);
}
}
void setValue(int key, int value)
{
set[key] = value;
}
int getValue(int key, int value)
{
return set[key];
}
};
#包括
#包括
使用名称空间std;
类位集
{
私人:
整数大小;
公众:
向量集;
整型运算符[](整型索引){
返回集[索引];
}
位集(int nsize=0)
{
cout该问题与操作符[]
的实现无关。请注意,您已声明a
为
BitSet *a;
所以你写的时候,
cout << a[5] << endl;
或者,更好的方法是,只声明位集
,而不将其作为指针
希望这能有所帮助!谢谢,很有效。感谢jxh解决了我的第一个问题。您想要和ostream操作员联系吗
cout << a[5] << endl;
cout << (*a)[5] << endl