【问题标题】:Pointer to a class with array indexing operator overload指向具有数组索引运算符重载的类的指针
【发布时间】:2018-10-17 09:18:10
【问题描述】:

我有一个类重载了数组索引运算符[]。现在我必须创建一个指向该类的指针,如何使用指向该类的指针来使用索引运算符 []。以下代码工作正常,但如果我取消注释 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;
}

【问题讨论】:

  • 好吧,既然它是一个指针,你需要先取消引用它。所以:(*a)[i] = i+50;
  • (*a)[i]a-&gt;operator[](i)

标签: c++ arrays class pointers operator-overloading


【解决方案1】:

带有以下声明:

basicVector *a = new basicVector(10);

您可以取消引用指针(首选):

uint8_t n = (*a)[5];

或使用operator 语法调用运算符:

uint8_t n = a->operator[](5);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多