Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 创建可以包含不同类的变量_C++_Class_Variables - Fatal编程技术网

C++ 创建可以包含不同类的变量

C++ 创建可以包含不同类的变量,c++,class,variables,C++,Class,Variables,我想创建一个类似于enum的变量,它是指向a类、B类或空类的指针 它看起来像这样: #include "A.h" #include "B.h" enum Foo{ A, B, Empty }; int main(){ Foo bar = new A(); bar.print(); bar = Empty; if ( bar == Empty ) // do stuff return 0; } int main(){ Base * bar =

我想创建一个类似于
enum
的变量,它是指向a类、B类或空类的指针

它看起来像这样:

#include "A.h"
#include "B.h"


enum Foo{
 A,
 B,
 Empty
};

int main(){
  Foo bar = new A();

  bar.print();

  bar = Empty;
  if ( bar == Empty )
    // do stuff
  return 0;

}
int main(){
    Base * bar = new A();

    bar->print();

    delete bar; //to release A
    bar = 0;

    if(bar == 0){
       // do stuff   
    }
     return 0;
}

有这样的可能吗?我该怎么做呢?

您考虑过使用多态性吗

我想指针最适合这里。指向基类的指针可以指向它的一个子类,也可以指向null/0——这正是您想要的

如果您的
A
B
可以从公共基类继承:

class A : public Base{...};
class B : public Base{...};
您的代码可能如下所示:

#include "A.h"
#include "B.h"


enum Foo{
 A,
 B,
 Empty
};

int main(){
  Foo bar = new A();

  bar.print();

  bar = Empty;
  if ( bar == Empty )
    // do stuff
  return 0;

}
int main(){
    Base * bar = new A();

    bar->print();

    delete bar; //to release A
    bar = 0;

    if(bar == 0){
       // do stuff   
    }
     return 0;
}
另外,要像这样使用
bar->print()
,请确保首先在
Base
类中声明了它(这样编译器就知道分配给
Base*bar
的任何类型都可以使用它,例如:

class Base{
public:
    virtual void print(){...} 
};

谢谢你的主意,这件更合适。