C ++ noob问题:指针和重载[]

时间:2010-07-19 00:10:02

标签: c++ pointers operator-overloading dereference

我一直在盯着这一段时间并没有走得太远。 FruitBasketFactory,FruitBasket和Fruit是我正在使用的API中的三个类。我的目标是制作一个水果篮,然后取回水果。根据FruitBasketFactory.hpp:

const FruitBasket* getFruitBasket() const;

然后在FruitBasket.hpp

size_t getNumFruits() const;
const Fruit& operator[](size_t index) const;

所以这是我的初始代码:

FruitBasketFactory fruitBasketFactory;
//since I want an object rather than a pointer I attempt to dereference the pointer
const FruitBasket fruitBasket = *(fruitBasketFactory.getFruitBasket());

但是在这里我收到错误“错误C2248:'FruitBasket :: FruitBasket':无法访问类'FruitBasket'中声明的私有成员”。这不应该起作用吗?

所以,很好......我修改了我的代码。

FruitBasketFactory fruitBasketFactory;
const FruitBasket* fruitBasket = fruitBasketFactory.getFruitBasket();

if(fruitBasket->getNumFruits() > 0) {
    //using (*fruitBasket)[0] seems silly
    const Fruit fruit = (*fruitBasket)[0];
}

失败“错误C2248:'Fruit :: Fruit':无法访问”Fruit'类中声明的私有成员“

所以,另一次返工

FruitBasketFactory fruitBasketFactory;
const FruitBasket* fruitBasket = fruitBasketFactory.getFruitBasket();

if(fruitBasket->getNumFruits() > 0) {
    //this is just ludicrous ... I'm doing something wrong
    const Fruit* fruit = &(fruitBasket->operator[](0));
}

这段代码看起来很傻,它实际上是有效的。但为什么我可以做我认为应该是最明显的事情呢?

FruitBasketFactory fruitBasketFactory;
const FruitBasket fruitBasket = *(fruitBasketFactory.getFruitBasket());

if(fruitBasket.getNumFruits() > 0) {
    const Fruit fruit = fruitBasket[0];
}

分辨率:

复制构造函数确实被FruitBasket和Fruit阻止了。我能够通过创建引用来绕过它们,如下所示:

FruitBasketFactory fruitBasketFactory;
const FruitBasket& fruitBasket = *(fruitBasketFactory.getFruitBasket());

if(fruitBasket.getNumFruits() > 0) {
    const Fruit& fruit = fruitBasket[0];
}

1 个答案:

答案 0 :(得分:1)

  

但在这里我收到错误error C2248: 'FruitBasket::FruitBasket' : cannot access private member declared in class 'FruitBasket'

FruitBasket的复制构造函数无法访问。您是否已将此类的复制构造函数声明为私有或受保护?此类是否有任何不可复制的基础或成员(即,没有可公开访问的复制构造函数)?

要回答你的上一个问题,请:

const Fruit* fruit = &(fruitBasket->operator[](0));

可以更合理地写成:

const Fruit* fruit = &(*fruitBasket)[0];

必须取消引用指针,以便将下标运算符应用于类类型FruitBasket对象,而不是指向FruitBasket的指针。

如果应用指针的下标,则使用内置的下标运算符,并将指针视为指向FruitBasket个对象数组的指针。