c++ 小结之友元类访问非静态成员
友元类访问被关联类的非静态成员
友元类不能直接访问被关联类的数据,如:
template <typename Object>
class Table
{
private:
int a;
...
public:
class Table_2
{
protected:
friend class Table<Object>;
...
public:
void method( ) const
{ std::cout << a; } // 错误的做法
};
...
};
这么做是不可以的。原因在于类未被实例化,所访问的应当是具体的类对象,所以友元类访问被关联类的数据,应当传递一个指向被关联类的指针或者引用。如:
template <typename Object>
class Table
{
private:
int a;
...
public:
class Table_2
{
protected:
friend class Table<Object>;
const Table<Object> * t;
...
public:
void method( ) const
{ std::cout << t->a; } // 这里省略了友元类的构造函数
int value( ) const
{ return t->a; } // 错误
...
};
...
};
在友元类的构造函数中传递这个指针即可,由于友元类与被关联类是一起使用的,所以通常传递this或者*this,取决于采用指针还是引用。另一个需要注意的是const限定符,因为指针或者引用被const限定以后,其中的值也是const,所以要注意返回值。比如value( )函数,其中的t->a是const类型,因为t是const指针,所以t->a也就是const数据了,要么返回值改成const int要么使用const_case去除const限定。
const int value( ) const
{ return t->a; }
int value( ) const
{ return const_case<int>( t->a ); }
浙公网安备 33010602011771号