java C++“对象”类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11747439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ "Object" class
提问by user142852
In Java, there is a generic class called "Object", in which all classes are a subclass of. I am trying to make a linked list library (for a school project), and I have managed it to make it work for only one type, but not multiple, so is there anything similar to that?
在Java中,有一个泛型类叫做“Object”,其中所有的类都是其子类。我正在尝试制作一个链表库(用于学校项目),并且我已经设法使其仅适用于一种类型,而不适用于多种类型,那么有没有类似的东西?
EDIT: I would post the code, but I don't have it on me at this time.
编辑:我会发布代码,但目前我没有。
回答by Luchian Grigore
There's no generic base class in C++, no.
C++ 中没有通用基类,没有。
You can implement your own and derive your classes from it, but you have to keep collections of pointers (or smart pointers) to take advantage of polymorphism.
您可以实现自己的类并从中派生类,但是您必须保留指针(或智能指针)的集合以利用多态性。
EDIT: After re-analyzing your question, I have to point out std::list
.
编辑:重新分析你的问题后,我必须指出std::list
。
If you want a list which you can specialize on multiple types, you use templates (and std::list
is a template):
如果您想要一个可以专用于多种类型的列表,您可以使用模板(并且std::list
是一个模板):
std::list<classA> a;
std::list<classB> b;
If you want a list which can hold different types in a single instance, you take the base class approach:
如果您想要一个可以在单个实例中包含不同类型的列表,您可以采用基类方法:
std::list<Base*> x;
回答by MuffinMan
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;
}
};
Then make a subclass of it
然后创建它的子类