2

这就是问题所在——我有两个这样的类:

class A
{
  //some fields and methods 
   void niceMethod();
};

class B : public A
{
   void niceMethod();
};

class C : public A
{
   void niceMethod();
};

和功能

void myFunc(A** arrayOfABC);

//双*是注意我要修改参数。

我想做:

(*arrayOfABC)[i].niceMethod();

在我的函数中,当我将 Bs 或 Cs 数组传递给函数时,会完成不同的事情。

但后来我试着这样称呼它

 B* bees = NULL;
    myFunc(&bees);

我有“B** 的参数类型与 A** 类型的参数不兼容”。

我知道我可以将 B 或 C 作为 A 传递给 f(A) 之类的函数,但是指针有什么问题?

4

2 回答 2

3

编译器是对的,确实不兼容。考虑一下:

B* bees = new B[2];
myFunc(&bees); // Imagine that it's allowed

现在在myFunc你里面这样做:

void myFunc(A** arrayOfABC) {
    // This is OK:
    arrayOfABC[0] = new C();
}

这应该是允许的,因为Cextends AmyFunc但是,从您返回时bees将包含 a C,这是不好的。

要解决此问题,请创建一个 数组A*,并用指向 的指针填充它B

PS不要忘记制作niceMethod虚拟,否则它不会按您期望的方式工作。

于 2012-05-31T15:25:27.683 回答
2

You can convert B* to A*, but not B** to A**.

Suppose A is fruit and B is apple, then A* is a little arrow that can point to a fruit (any fruit) and B* is a little arrow that can point to an apple (and only an apple). You can take an apple arrow, relabel it as a fruit arrow, and give it to somebody that expects fruit arrows. It indeed points to a fruit because an apple is a kind of a fruit. So far so good, no surprises here.

Now A** is a little arrow that can point to a little arrow that can point to a fruit (any fruit), and B** is a little arrow that can point to a little arrow that can point to an apple (and only an apple). What will happen if you take the latter, and give it to somebody who expects the former? That person can go along the arrow that can point to an arrow that can point to a fruit (any fruit!), take that second arrow, and turn it around and make it point to a banana.

Now the unfortunate apple guy guy who used to have a double-apple-arrow goes along the first arrow, then goes along the second arrow that ought to point to an apple, and finds a banana there, a fruit he sees the first time in his miserable life. That's a pretty unfortunate situation if you ask me. We shouldn't be surprised if things go bananas from this point on!

于 2012-05-31T15:43:56.373 回答