[英]C++ "Object" class
在Java中,有一个泛型类叫做“Object”,其中所有的类都是其子类。 我正在尝试制作一个链表库(用于学校项目),并且我已经设法使其仅适用于一种类型,而不适用于多种类型,那么有没有类似的东西?
编辑:我会发布代码,但目前我没有。
C++ 中没有通用基类,没有。
您可以实现自己的类并从中派生类,但是您必须保留指针(或智能指针)的集合以利用多态性。
编辑:重新分析您的问题后,我必须指出std::list
。
如果你想要一个可以专攻多种类型的列表,你可以使用模板( std::list
是一个模板):
std::list<classA> a;
std::list<classB> b;
如果您想要一个可以在单个实例中包含不同类型的列表,您可以采用基类方法:
std::list<Base*> x;
class Object{
protected:
void * Value;
public:
template <class Type>
void operator = (Type Value){
this->Value = (void*)Value;
}
template <>
void operator = <string>(string Value){
this->Value = (void*)Value.c_str();
}
template <class Type>
bool operator == (Type Value2){
return (int)(void*)Value2==(int)(void*)this->Value;
}
template<>
bool operator == <Object> (Object Value2){
return Value2.Value==this->Value;
}
template <class ReturnType>
ReturnType Get(){
return (ReturnType)this->Value;
}
template <>
string Get(){
string str = (const char*)this->Value;
return str;
}
template <>
void* Get(){
return this->Value;
}
void Print(){
cout << (signed)this->Value << endl;
}
};
然后创建它的子类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.