多态向量C++ – 没有用于调用'compare'的匹配成员函数



我有一个抽象类Type和两个继承的类Type_A和Type_B。我已经使用虚拟函数实现了某种比较。我想制作一个包含指向Type_a和Type_B的指针的多态向量。然后我想从这些向量中挑选两个对象并进行比较,但我得到了以下错误:

class Type {
public:
virtual bool compare(const Type_A &other) = 0;
virtual bool compare(const Type_B &other) = 0;
};
class Type_A : public Type {
string data;
public:
Type_A(string given_data) {
data = given_data;
}
bool compare(const Type_A& other)  {
return (data > other.data);
}
bool compare(const Type_B& other) {
return false;
}
};
class Type_B : public Type {
public:
int data;
Type_B(string given_data) {
data = stoi(given_data);
}
bool compare(const Type_B& other)  {
return (data > other.data);
}
bool compare(const Type_A& other) {
return false;
}
};
int main() {
vector<Type*> vec1;
vector<Type*> vec2;
Type_A test1("ab");
Type_B test2("ba");
vec1.push_back(&test1);
vec2.push_back(&test2);
cout << vec1[0]->compare(vec2[0]) << endl; //ERROR: no matching member function for call to 'compare'

}

有两个问题。一种是vec2[0]是指针类型,但compare需要常规对象。另一个是Type.compare期望Type_AType_B对象,而不是Type对象。Do:

vec1[0]->compare(*(Type_B *) vec2[0])

最新更新