指向基类的成员指针
全部。我无法理解为什么下面的代码需要强制转换才能工作。有人可以解释一下吗?
class Base {
};
class Derived : public Base {
};
class Class {
public:
Derived member;
};
...
Derived obj;
Base *ptrObj = &obj; // ok, no cast needed
Derived Class::* ptr = &Class::member; // ok
Base Class::* ptr = &Class::member; // wrong, need cast, why?
all. I can't undestand why the bellow code need a cast to work. Someone can explain it?
class Base {
};
class Derived : public Base {
};
class Class {
public:
Derived member;
};
...
Derived obj;
Base *ptrObj = &obj; // ok, no cast needed
Derived Class::* ptr = &Class::member; // ok
Base Class::* ptr = &Class::member; // wrong, need cast, why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为如果允许
Base
(协变),那么你就可以这样做,这是一个禁忌:同时,指向成员的指针也不能是逆变的,因为否则你可以这样做,这也是一个禁忌:
因此,指向成员的指针既不是协变也不是逆变,而是不变的:类型必须完全匹配。
Because if
Base
were allowed (covariant), you could then do this, which is a no-no:At the same time, pointers-to-members cannot be contravariant either, because otherwise you could do this, which is also a no-no:
So, pointers-to-members are neither covariant nor contravariant, but are invariant: the type must match exactly.
好吧,我明白你的意思了,克里斯,但是你的第一个例子适用于普通指针。为什么它不适用于成员指针?请参阅下面的代码。
第二个示例即使对于普通指针也不起作用,因为不进行强制转换就不允许向下转换。所以我认为这不应该是一个解释。
Ok, I got your point Chris, but your first example works for ordinary pointers. Why should it not work for member pointers too? See the code bellow.
The second example will not work even for ordinary pointers, since downcasting is not allowed without cast. So I don't think that should be a explanation.