我有一个简单的类层次结构,包含基类和派生类.基类有两个派生类调用的受保护成员.来自最近的一些C#体验,我认为最好让界面更流畅并允许链接方法调用,所以不用调用this->A(),那么this->B()你可以调用this->A()->B().但是,以下代码将无法编译:
#include <iostream>
class Base
{
protected:
Base* A()
{
std::cout << "A called." << std::endl;
return this;
}
Base* B()
{
std::cout << "B called." << std::endl;
return this;
}
};
class Derived : public Base
{
public:
void Test()
{
// Base::A and Base::B are private here.
this->A() // This works fine
->B(); // Suddenly I cannot access my own private method?
}
};
int main()
{
Derived d;
d.Test();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这会产生以下编译器错误:
main.cpp: In member function 'void Derived::Test()':
main.cpp:12:15: error: 'Base* Base::B()' is protected
Base* B()
^
main.cpp:26:21: error: within this context
->B(); // Suddenly I cannot access my own private method?
^
Run Code Online (Sandbox Code Playgroud)
我也尝试将基类方法设为虚拟,但这没有帮助.
我的C++足够生疏,我似乎无法弄清楚这里发生了什么,所以非常感谢帮助.此外,我想知道这是不是一个坏主意,因为C++ != C#和C++ - 人们不习惯这样流畅的界面.
类中的受保护成员只能通过派生类从派生类访问,即通过派生类的对象,或引用或指向该派生类.
返回类型A()是Base*,它不是派生类,这就是您无法访问其受保护成员的原因.编译器不会跟踪它实际上是指同一个对象.