基类的成员指针 [英] Member Pointer to Base Class

查看:174
本文介绍了基类的成员指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有。我无法理解为什么波纹管代码需要一个演员才能工作。有人可以解释一下吗?

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?


推荐答案

因为如果 Base (协变),你可以这样做,这是一个禁忌:

Because if Base were allowed (covariant), you could then do this, which is a no-no:

Base Class::* ptr = &Class::member;
Class obj;
obj.*ptr = Base();   // <-- assigned a Base into a Derived field?!

同时,指向成员的指针也不能逆变,因为否则你可以做到这一点,这也是禁忌:

At the same time, pointers-to-members cannot be contravariant either, because otherwise you could do this, which is also a no-no:

struct Class2 {
    Base member;
};

Derived Class2::* ptr2 = &Class2::member;
Class2 obj2;
obj2.member = Base();
Derived& d = obj2.*ptr2;  // <-- assigned a Base into a Derived

因此,指向成员的指针既不是协变或逆变,但不变:类型必须完全匹配。

So, pointers-to-members are neither covariant nor contravariant, but are invariant: the type must match exactly.

这篇关于基类的成员指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆