在这种情况下,以下哪一项是正确的?

时间:2015-07-26 21:02:03

标签: c++ oop

我在测试中被问到这个问题而且我感到困惑:

Q. If the following is a part of a completely fine C++ program:

     p = new bicycle("Hello world", 2,4);

then, which of the following is true?

1. p is a pointer to a concrete class bicycle.
2. p is a pointer to a concrete class bicycle or some base class (abstract) of bicycle.
3. p is a pointer to a concrete class bicycle or some derived class of bicycle. 

Options: 
A) 1 only
B) 2 only
C) 3 only
D) 1 and 2 both

你能帮我解决一下这个问题的正确方法吗?我认为这将是:bicycle * p = new ....

1 个答案:

答案 0 :(得分:1)

正确答案是 B

bicycle *p = new bicycle();

无论如何,这可能是p的有效声明。

此外,我们可以将指针存储到基类的指针中。 因此,例如,有一个类Cyclebicycle继承Cycle然后::

Cycle *p = new bicycle(); 也是一个有效的陈述

这意味着p可以指向具体类自行车 OR 某些自行车基类(此处为循环)。因此,答案B

此外,答案不能是 D ,因为p不能是具体指针 AND 也是指向基类的指针。感谢@bogdan。

虽然很多事情仍然不清楚。考虑p也可以是void *(再次感谢@bogdan:P),这个问题明显错过了。

相关问题