获取指向通过 using 声明公开的派生类成员的指针

问题描述 投票:0回答:1

考虑一个具有几个公共字段的基类和一个派生类,该派生类私有地继承基类,并通过

using
声明将继承的字段之一设为公共。我需要使用成员指针访问派生类的这个公共字段。这是一些代码:

#include <iostream>

class Base
{
public:
    int derived_public_field = 1;
    int derived_private_field = 1;
};


class Derived : private Base
{
public:
    using Base::derived_public_field;
};


int main() {
    Derived d;
    int Derived::* member_ptr = &Derived::derived_public_field;
    d.*member_ptr = 2;
    std::cout << d.derived_public_field << '\n';
}

这不起作用,因为

&Derived::derived_public_field
表达式会导致编译器(尝试过 Clang 和 GCC)认为我正在尝试访问无法访问的基础。海湾合作委员会 说:

error: 'Base' is an inaccessible base of 'Derived'

有没有办法让编译器看到

derived_public_field
实际上是可访问的?

c++ oop inheritance pointer-to-member
1个回答
0
投票

&Derived::derived_public_field
实际上是
&Base::derived_public_field

然后从

int Base::*
int Derived::*
的转换由于访问失败。

正如 Eljay 在评论中建议的那样,您可以在

Derived
中添加一个(静态)方法来解决该问题:

class Derived : private Base
{
public:
    // using Base::derived_public_field; // Not needed for below

    static auto get_derived_public_field_memptr() -> int Derived::*
    {
        return &Derived::derived_public_field;
    }
};

演示

© www.soinside.com 2019 - 2024. All rights reserved.