[英]how to use a base class pointer refer to a derived class member?
class a{};
class b : public class a{
public:
int c;
};
a* var = new b;
var->c=2;
Last line is not correct. 最后一行不正确。 Is it possible to refer to the derived class member? 是否可以引用派生的类成员?
If the member is not in the base class, you should not be allowed to access it and it should give a compilation error. 如果成员不在基类中,则不应允许您访问该成员,并且应给出编译错误。 To access a member of derived class, you can typecast it to the derived class. 要访问派生类的成员,可以将其类型转换为派生类。
class a{};
class b : public class a{
public:
int c;
};
a* var = new b;
((b*)var)->c=2;
while var is ab object at compile time the compiler does not know that so you have to cast it to ab object or pointer like this. 尽管var在编译时是ab对象,但编译器并不知道,因此您必须将其强制转换为ab对象或指针。
(*(b*)var).c = 2;
((b*)var)->c = 2;
My computer science teacher explained that treat two cases when doing polymorphism run-time and compile time 我的计算机科学老师解释说,在执行多态运行时和编译时要处理两种情况
Hope this helps. 希望这可以帮助。
您可以使用static_cast从Base降到Derived,然后访问该成员。
static_cast<b*>(var)->c = 2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.