我有一个重载了数组索引operator []的类。现在我必须创建一个指向该类的指针,如何使用索引operator []使用指向该类的指针。以下代码工作正常,但如果我取消注释 basicVector * a = new basicVector(10)行并将 - > 代替。,我收到错误。
请参阅this链接了解编译器设置和代码。
#include <iostream> // std::cout
#include <queue> // std::queue
#include <string>
#include <string.h>
#include <stdint.h>
#include <vector>
using namespace std;
class basicVector
{
private:
uint32_t array_size;
uint8_t * array;
public:
basicVector(uint32_t n);
~basicVector();
uint32_t size();
uint8_t * front();
uint8_t& operator[](uint32_t i);
};
basicVector::basicVector(uint32_t n)
{
array_size = n;
array = new uint8_t[n];
}
basicVector::~basicVector()
{
delete [] array;
}
uint32_t basicVector::size()
{
return array_size;
}
uint8_t * basicVector::front()
{
return array;
}
uint8_t& basicVector::operator[](uint32_t i)
{
return array[i];
}
int main ()
{ //basicVector * a = new basicVector(10);
basicVector a(10);
cout <<a.size()<<endl;
for(uint8_t i=0; i < a.size(); i++)
{ a[i] = i+50; //how to do this correctly when "a" is pointer?
}
uint8_t * b = &a[3]; //how to do this correctly when "a" is pointer?
*b = 45;
for(uint32_t i=0; i < a.size(); i++)
{ cout<<a[i]<<endl; //how to do this correctly when "a" is pointer?
}
return 0;
}
答案 0 :(得分:1)
使用以下声明:
basicVector *a = new basicVector(10);
您可以取消引用指针(首选):
uint8_t n = (*a)[5];
或者使用operator
语法调用运算符:
uint8_t n = a->operator[](5);