pClass1 = (Class1*)pBase->next 不带 (Class1*) 强制转换
类基类 { 接下来是基地*; 我
class Class1 : Base
{
}
Base* pBase = new Base();
Class1* pTest = new Class1();
pBase->next = pTest;
Class1* pClass1;
pClass1 = (Class1*)pBase->next;
希望能够编写
pClass1 = pBase->next;
并且不会出现编译错误 C2440(无法转换)。或者换句话说,我希望 pClass1 指向 pBase->next 指向的类。
某些运算符重载是否可能?怎么做呢?
class Base
{
Base* next;
}
class Class1 : Base
{
}
Base* pBase = new Base();
Class1* pTest = new Class1();
pBase->next = pTest;
Class1* pClass1;
pClass1 = (Class1*)pBase->next;
I want to be able to write
pClass1 = pBase->next;
and get no compilation error C2440 (cannot convert). Or in other words I want pClass1 point to a class that pBase->next points to.
Is it possible with some operator overloading? How to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果 - 在开发时 - 您确定 next 指向 Class1 的实例,请将 next 设置为 Class1 指针而不是 Base 指针。
如果您不确定,并且只有在编译时才知道,则必须使用动态强制转换(可能 next 稍后会指向 Class2 实例)。
If - at development time - you're sure that next points to an instance of Class1, make next a Class1 pointer instead of a Base pointer.
If you're not sure, and you only know it at compile time, you have to use a dynamic cast (possibly next will point to a Class2 instance later).
我能得到的最接近你想要的东西是:
and:
但这确实是在搞乱C++,你以后会为此付出惨重的代价。只需使用帕特里克提到的演员阵容之一即可。
The closest I can get to what you are after is this:
and:
But this is really messing around with C++ in ways that you will pay for severely later. Just use one of the casts mentioned by Patrick.