C++ "Object"类

C++ "Object" class

本文关键字:Object C++      更新时间:2023-10-16

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

};

然后使其成为的子类

相关文章: