我有一个带有基类和派生类的简单类层次结构。基具有派生类调用的两个受保护的成员。根据最近的一些C#经验,我认为最好能使接口更加流畅,并允许方法调用的链接,这样this->B()
就可以调用this->A()->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;
}
这会产生以下编译器错误:
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?
^
我还尝试将基类方法变成虚拟的,但这并没有帮助。
我的C++已经生锈了,我似乎不知道这里到底发生了什么,所以我会非常感激你的帮助。另外,我想知道这是不是个坏主意,因为C++ != C#
和C++-人们不习惯这样流畅的界面。
发布于 2014-02-04 02:33:03
类中的受保护成员只能通过派生类(即通过派生类的对象、引用或指针)从派生类访问。
A()
的返回类型是Base*
,它不是派生类,这就是不能访问其受保护成员的原因。编译器不跟踪它是否真正引用了同一个对象。
发布于 2014-02-04 02:26:38
是的,不能从Base
类的Base *
中调用受保护的方法。您可以认为受保护的方法是私有的,不同的是它们也成为派生类的私有方法。
发布于 2014-02-04 02:34:06
这是正确的行为,您不能为不同的类调用受保护的函数,您只能通过派生类进行调用,因为当调用this->A()
时,它返回一个Base*,这是一个不同的类。原因是,如果你做了类似的事情
class Derived : public Base
{
public:
void Test()
{
baseInstance->B(); // this shouldn't be possible. If the case was you can call it through a pointer or an object this would be possible.
}
Base* baseInstance;
};
此外,还可以指出派生this
和基可能没有相同的地址,可能有不同的地址。当您实际将Base*
转换为Derived*
时,编译器将处理地址上的差异,这使得它能够工作,这就是为什么它是像这样做的static_cast<Derived*>(this->A())->B();
https://stackoverflow.com/questions/21549681
复制相似问题