C++ 继承 : defining a pointer to either derived or base class

标签 c++ class pointers inheritance

如果我有一个来自基类的派生类,并且我想根据标志为它们中的任何一个的对象分配一个指针,那么指向所选对象的指针的定义应该是什么。

例子:

void main(int argc, char* argv[])
{
   class Base B;
   class Derived D;
   class Base *P;  /* My question is output this definition */
   int flag;   /* This will be an input */
   if(flag)
      P = &B;   /* Should refer to the base class B */
   else
      P = &D;   /* Should refer to the derived class D
   /* Then I'd use P in the rest of my code */ 
} 

我的问题是,类指针 P 如何定义为能够基于标志“flag”引用 B(基类)或 D(派生类)?

最佳答案

假设您的代码是基本形式:

class Base
{
public:
   virtual ~Base() {}
};

class Derived : public Base
{};

然后 Derived 根据语言规则是 Base,因此指向基类的指针可以包含 Derived 或一个 Base

Base* p = nullptr;
Base b;
Derived d;

if(flag == UseBase)
{    
   // Works
   p = &b;
}
else if(flag == UseDerived)
{
   // also works
   p = &d;
}

就是说,Base 不是 Derived,因此反向 (Derived* pd = &b) 不会像上面写的那样工作.

关于C++ 继承 : defining a pointer to either derived or base class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21898541/

相关文章:

c++ - 在 GUI 设计中避免 dynamic_cast

c++ - 质数函数 C++

c++ - 与多态性一起使用的数组的奇怪输出

javascript - 数组的嵌套类,想要获取外部数组的索引

python - 动态创建类 - Python

c++ - double[][] 不等于 **double 吗?

c - 在 yacc 中返回指针时出现段错误

C++:派生类对象被析构时释放动态内存

php - 是否可以重新定义 PHP 常量?

c++ - 初始化指针,c 和 c++ 编译器之间的区别 (gcc-4.3.4)