简体   繁体   English

如何访问受保护的成员

[英]How to access protected members

I have a MockAlgoController class which has protected inheritance of ControllerMockParams .我有一个MockAlgoController class ,它保护了ControllerMockParams的 inheritance 。 How to access these protected fields outside, ie when asserting in tests?如何在外部访问这些受保护的字段,即在测试中断言时?

struct ControllerMockParams
{
    int numCtx{0};
    MockAlgo firstAlgo{Interface::first, numCtx};
    MockAlgo secondAlgo{Interface::second, numCtx};
}


class MockAlgoController : protected ControllerMockParams, public AlgoController
{
public:
    MockAlgoController()
        : AlgoController(
              ControllerMockParams::firstAlgo,
              ControllerMockParams::secondAlgo)
    {
    }
    MOCK_METHOD0(foo(), void());
// (...)

}

How do I expose the firstAlgo and secondAlgo so they are accessible outside, ie for assertion:如何公开firstAlgosecondAlgo以便它们可以在外部访问,即用于断言:

EXPECT_CALL(mockAlgoController.firstAlgo, bar()) // bar() is defined in MockAlgo class.

To access protected fields outside you must not use protected in the first place.要访问外部受保护的字段,您首先不能使用protected So your code should be like:所以你的代码应该是这样的:

class MockAlgoController : public ControllerMockParams, public AlgoController
{
public:
    MockAlgoController()
        : AlgoController(
              ControllerMockParams::firstAlgo,
              ControllerMockParams::secondAlgo)
    {
    }
    MOCK_METHOD0(foo(), void());
// (...)
}

When a class uses public member access specifier to derive from a base, all public members of the base class are accessible as public members of the derived class and all protected members of the base class are accessible as protected members of the derived class (private members of the base are never accessible unless friended) When a class uses public member access specifier to derive from a base, all public members of the base class are accessible as public members of the derived class and all protected members of the base class are accessible as protected members of the derived class (private members除非已加好友,否则基地永远无法访问)

See documentation: https://en.cppreference.com/w/cpp/language/derived_class请参阅文档: https://en.cppreference.com/w/cpp/language/derived_class

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM