简体   繁体   English

如何使用基类指针引用派生类成员?

[英]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.

相关问题 派生类不能使用成员指针来保护基类成员 - Derived class cannot use member pointer to protected base class member 对于具有使用基类指针的构造函数的派生类,如何引用基类指针? - For a derived class with a constructor that takes a base class pointer, how do I refer to the base class pointer? 指向派生 class 中的基 class 作为成员变量的指针 - Pointer to base class in derived class as a member variable 如何注册派生的 class 成员 function 指针与基数 class - How to register a derived class member function pointer with a base class 无法将“指向派生类的成员指针”转换为“指向基类的成员指针” - Cannot cast “member pointer to derived class” to “member pointer to base class” 如何引用基类的派生类? - how to refer to a base class's derived class? 具有派生成员的基类的唯一指针 - unique pointer of base class with derived member 如何通过派生的指针在基类中调用模板成员函数 - How to call template member function in the base class by the derived pointer 如何通过基指针访问派生 class 的成员函数? - How to access member functions of a derived class through a base pointer? 无法在派生的模板类中引用基类成员 - Can't refer to base-class member in derived template class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM