【发布时间】:2019-09-16 20:40:01
【问题描述】:
我有一个抽象父类,我们称它为 A,以及从它继承的三个子类:a_B、a_C 和 a_D。我有一个排序方法,它应该能够根据从父级 A 继承的评级属性对这些类(a_B、a_C 或 a_D)中的任何一个的数组进行排序。
但是,我在实现这一点时遇到了麻烦。
这基本上是我所拥有的:
class A {
protected:
int rating;
A(int r) {
this->rating = r;
}
public:
int getRating() {
return rating;
}
virtual void abstractStuff() = 0;
}
class a_B : public A {
int property;
public:
a_B(int r, int p) : A(r) {
this->property = p;
}
void abstractStuff() {
cout << "a_B" << endl;
}
}
class a_C : public A {
float property;
public:
a_B(int r, float p) : A(r) {
this->property = p;
}
void abstractStuff() {
cout << "a_C" << endl;
}
}
class a_D : public A {
string property;
public:
a_B(int r, string p) : A(r) {
this->property = p;
}
void abstractStuff() {
cout << "a_D" << endl;
}
}
void sort(A* arr[]) {
//sort implementation
}
int main() {
a_B arr[5];
//code to give each element of arr unique properties
sort (arr); //doesn't work; this is where I'm kind of unclear about what to do
}
我对 arr 进行排序的最后一部分不清楚。我不确定是否应该将 a_B* 作为指针传递,或者将其转换为 A 类型,例如 (A) a_B 或 (A*) a_B 或类似的东西。
编辑:
编译器给我一个invalid conversion from a_B to A**的错误。
【问题讨论】:
-
您的基类构造函数应该是公共的,
rating变量应该是私有的。使用 protected 是一种代码味道。
标签: c++ pointers parameter-passing