C++"对象"类

use*_*852 18 c++ java class linked-list object

在Java中,有一个名为"Object"的泛型类,其中所有类都是其子类.我正在尝试创建一个链表库(对于一个学校项目),我已经设法让它只适用于一种类型,但不是多种,所以有什么类似的东西吗?

编辑:我会发布代码,但我现在没有它.

Luc*_*ore 27

C++中没有通用基类,没有.

您可以实现自己的类并从中派生类,但是您必须保留指针(或智能指针)的集合以利用多态性.

编辑:重新分析您的问题后,我必须指出std::list.

如果你想要一个可以专注于多种类型的列表,你可以使用模板(并且std::list是一个模板):

std::list<classA> a;
std::list<classB> b;
Run Code Online (Sandbox Code Playgroud)

如果您想要一个可以在单个实例中包含不同类型的列表,则采用基类方法:

std::list<Base*> x;
Run Code Online (Sandbox Code Playgroud)

  • 或者您可以使用许多现有库中的一个与God对象.无论如何,当你要理解这个决定的全部含义时,你很有可能会想到一个混乱而痛苦的自杀.*//喜欢一切**其他**关于ROOT* (2认同)

小智 5

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;
}


};
Run Code Online (Sandbox Code Playgroud)

然后创建它的子类