下面哪个选项在这种情况下是正确的?

Which of the following will be true in this case?

本文关键字:这种情况下 选项      更新时间:2023-10-16

我在测试中被问到这个问题,我不知怎么弄糊涂了:

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 ....

正确答案是B

bicycle *p = new bicycle();

对于p,这可以是一个有效的声明。

此外,可以将指向派生类的指针存储在基类的指针中。例如,有一个类Cycle, bicycle继承Cycle,然后::

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

这意味着p可以是指向具体类bicycle 的某个基类bicycle(这里是cycle)的指针。因此,答案是B

而且,答案不能是D,因为p不能是一个具体指针也是一个基类指针。感谢@bogdan。

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