如何在派生类数据中使用基类进行比较



我在C++中有基类和派生类
我想使用基类的指针来确定派生类的数据是否相同。

枚举类型

enum class FruitType: int{
Apple,
Orange,
};

基本类

class Base{
public:
Base(FruitType t): fruit_type(t){}
FruitType fruit_type;
};

派生类

class Apple : public Base{
public:
Apple(int i): Base(FruitType::Apple), foo(i){}
int foo;
};
class Orange : public Base{
public:
Orange(float f): Base(FruitType::Orange), bar(f){}
float bar;
}; 

初始化

// initialize
std::vector<Base*> fruit_list_ = { 
new Apple(42),
new Orange(0.f),
new Apple(1) };

有什么方法可以用HasSameData((进行检查吗?

Base* HasSameData(const Base* pCompare){
for (const auto& list : fruit_list_) 
{
if( pCompare->fruit_type == list->fruit_type ){
// how to check same data...?
if( /* ... */ ){
return list;
}
}
}
return nullptr;
}
int main(){
// check same data
Base* pCompare = fruit_list_[2];
if(HasSameData(pCompare)){
// I want to return fruit_list_[2] pointer...
}
}

您可以在基本情况中添加一个抽象方法sameData()

class Base{
public:
Base(FruitType t): fruit_type(t){}
FruitType fruit_type;
virtual bool sameData(const Base& other) const = 0;
};

派生类中的覆盖:

class Apple : public Base{
public:
Apple(int i): Base(FruitType::Apple), foo(i){}
int foo;
virtual bool sameData(const Base& other) const {
const Apple* apple = dynamic_cast<const Apple*>(&other);
return apple && apple->foo == foo;
}
};
class Orange : public Base{
public:
Orange(float f): Base(FruitType::Orange), bar(f){}
float bar;
virtual bool sameData(const Base& other) const {
const Orange* orange = dynamic_cast<const Orange*>(&other);
return orange && orange->bar == bar;
}
};

并按如下方式使用:

// how to check same data...?                                       
if( pCompare->sameData(*list) ){

最简单的方法是使用虚拟函数来比较等式,并在虚拟函数的主体中实现比较逻辑。

class Base{
public:
Base(FruitType t): fruit_type(t){}
FruitType fruit_type;
virtual bool Equals(Base *other) const = 0;
};
class Apple : public Base{
public:
Apple(int i): Base(FruitType::Apple), foo(i){}
int foo;
bool Equals(Base *other) const override {
if (other->fruit_type != FruitType::Apple)
return false;
return foo == ((Apple*)other)->foo;
}
};
class Orange : public Base{
public:
Orange(float f): Base(FruitType::Orange), bar(f){}
float bar;
bool Equals(Base *other) const override {
if (other->fruit_type != FruitType::Orange)
return false;
return bar == ((Orange*)other)->bar;
}
}; 

然后这样写你的比较函数:

bool HasSameData(const Base* pCompare){
for (const Base *fruit : fruit_list_) 
if (pCompare->Equals(fruit))
return true;
return false;
}

最新更新