【发布时间】:2022-01-08 08:29:37
【问题描述】:
我不知道如何问这个问题,但基本上我将基类作为参数传递,如果参数是基类的派生类,我希望只能访问派生类中的属性
class A{
public:
bool isB = false;
int x = 69;
}
class B : public A{
public:
bool isB = true;
int y = 420;
}
void Print(A c){
if (c.isB)
cout << c.y << endl; //this will error as the class A has no y even though i will pass class B as an argument
else
cout << c.x << endl;
}
A a;
B b;
Print(a);
Print(b);
【问题讨论】:
-
您的
Print()函数是slicing 的输入参数,因此无法将B对象放入其中。您需要通过指针 (A*) 或引用 (A&) 来传递参数。然后Print()可以使用dynamic_cast访问B的成员。但这不是针对这种情况的好设计。您应该向A添加一个虚拟的print()方法,以便B覆盖,正如 this answer 所建议的那样。