类的“交友”是否会扩展到该类中声明的类?
我有以下代码,其中 A 类将 B 类声明为友元。在类 B 中声明的类 C 是否应该能够查看类 A 的私有声明/成员?
使用 CL 版本 16 (Visual Studio 2010) 进行编译时不会出现错误,但 gcc g++ 版本 4.1.1 会出现错误“typedef int A::T 在此上下文中是私有的”。
作为 typedef 的函数调用也会发生相同的行为(这就是我发现差异的方式)。
class A {
friend class B;
typedef int T;
};
class B {
A::T t; // ok
typedef A::T U; // ok
class C {
U u; // ok
A::T v; // compile error on gcc
};
};
我进行了简短的搜索,但未能找到正确的搜索词。我还没有通读该标准。之前是否有关于该主题的任何问题,或者 C++ 常见问题解答中提到过?标准暗示了哪种行为(如果有的话)?
I have the following code where class A declares class B as friend. Should class C, declared within class B, be able to view private declarations/members of class A?
It compiles without error with CL version 16 (Visual Studio 2010), but gcc g++ version 4.1.1 gives the error "typedef int A::T is private within this context".
The same behaviour occurs with functions calls as typedefs (which is how I discovered the difference).
class A {
friend class B;
typedef int T;
};
class B {
A::T t; // ok
typedef A::T U; // ok
class C {
U u; // ok
A::T v; // compile error on gcc
};
};
I have seearched briefly, but not been able to find the right search terms. I've yet to read through the standard. Are there any previous questions on the subject, or mentioned in the C++ FAQ? Which behaviour is imlpied by the standard, if either?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自标准文档,
$11.4.2
来自标准文档本身的示例,
因此它应该可以正常工作而不会出现任何错误。
From standard docs.,
$11.4.2
An example from the standard docs., themselves,
Hence it should work without any error.
原始标准 C++ 中似乎存在 一些缺陷03
根据 C++03 [pre CD1],您的代码不应编译,因为措辞和示例表明不能在友元类的嵌套成员中访问类的私有成员(授予友谊)。
C++11 给出了与 C++03 中相同的示例。对该示例所做的唯一更改是友元类的嵌套成员(类)能够访问授予友谊的类的私有成员。
另请参阅问题#45
There seems to be some defect in the original standard C++03
As per C++03 [pre CD1] your code should not compile because the wording and the example says that private members of a class(granting friendship) cannot be accessed in the nested member of the friend class.
C++11 gives the same example as in C++03. The only change made to that example is that the nested member(class) of the friend class is able to access the private member of the class granting friendship.
Also look at issue #45
Prasoon 提到了问题 #45...这种行为在 C++0x 中发生了变化。旧的行为是(11.7
[class.access.nest]
第 1 段):这清楚地表明,根据 C++03 规则,gcc 4.1 是正确的。 gcc 4.5 和 MSVC2010 使用 C++0x 规则。
Prasoon mentioned issue #45... this behavior changes in C++0x. The old behavior was (11.7
[class.access.nest]
paragraph 1):This clearly states that gcc 4.1 is correct according to the C++03 rules. gcc 4.5 and MSVC2010 are using the C++0x rules.