【发布时间】:2012-04-10 08:18:15
【问题描述】:
给出示例代码:
class Base {
public:
bool pub;
protected:
bool prot;
};
class Derived : private Base {
friend class MyFriend;
};
class MyFriend {
Derived _derived;
void test() {
// Does standard provide me access to _derived.pub and _derived.prot?
cout << "Am I allowed access to this: " << _derived.pub
<< " and this: " << _derived.prot;
}
};
作为朋友是否可以让我获得所有访问权限,就好像我是我作为朋友的类中的成员函数一样?换句话说,我可以得到基类的受保护成员和公共成员,因为我是朋友,所以我是私人继承的?
【问题讨论】:
-
看到您费尽心思编写示例代码,您是否尝试过编译它?这种答案很快就会在警告/缺乏中浮出水面。
-
@peachykeen:编译器接受的内容和标准所说的内容通常是不同的。此外,理论上,示例代码可能没有捕捉到细微之处。
-
@AdrianMcCarthy 这是真的。然而,当使用非标准特性时,许多编译器会发出警告,如果它违反标准和编译器的实现,你会得到一个简短而甜蜜的答案。虽然不是万无一失,但尝试一下也无妨。
标签: c++ inheritance private friend protected