以下代码用于检查指针转换:
#include <iostream>
#include <cstdlib>
using std::cout;
using std::endl;
class A
{
friend class B;
};
class B : private A { };
int main()
{
B *b = new B;
A *a = b;
cout << b << endl;
cout << a;
}
第11.2 / 4节N3797说:
A base class B of N is accessible at R, if
— an invented public member of B would be a public member of N, or
— R occurs in a member or friend of class N, and an invented public member of B would be a private or protected member of N, or
— R occurs in a member or friend of a class P derived from N, and an invented public member of B would be a private or protected member of P, or
— there exists a class S such that B is a base class of S accessible at R and S is a base class of N accessible at R
我认为A
是B
的可访问基类。
类型为“指向cv D的指针”的prvalue,其中D是类类型,可以是 转换为“指向cv B指针”类型的prvalue,其中B是基数 D类(第10条)如果B是无法进入的(第11条)或 模糊(10.2)D的基类,一个需要这个的程序 转换是不正确的
为什么我收到编译时错误?
main.cpp:17:12: error: cannot cast 'B' to its private base class 'A'
答案 0 :(得分:4)
为了使friend
声明能够使转化生效,它需要在友谊有效的范围内进行 - 也就是说,在B
自己的代码中。 A
将B
声明为朋友的事实在B
的定义之外无效。