Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在C+中重载索引运算符+;?_C++_Operator Overloading - Fatal编程技术网

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