静态方法做为友元的问题

On 2010年04月24日, in IT生活, by antmanler

在C++中一个类的友元函数或者友元类可以实现访问该类私有变量或者方法。但是对于静态方法使用声明友元类的方法却不能如愿,例如:

class Bar ;
class Foo {
public :
    // do some custom initialize
    static Bar *GetBar() { return new Bar() ;}
};

class Bar {
private:
    Bar(){ }
    // friend class Foo ;  will cause the compile error
    friend Bar *Foo::GetBar() ;
} ;

从上面的例子可以进一步理解类的静态成员的含义:属于类的上下文中,而不绑定于特定的对象(即无隐含的this指针)。

Tagged with: