来自模板类的朋友函数

nic*_*ole 9 c++ templates class friend

我有一个这样的课:

#include "Blarg.h"
// ...

class Foo : public Bar {    
  // ...
  static double m_value;
  // ...    
}; 
Run Code Online (Sandbox Code Playgroud)

而另一个像这样:

template<class X, class Y>
class Blarg : public Bar {
  // ...
  void SetValue(double _val) { Foo::m_value = _val; }
  // ...
};
Run Code Online (Sandbox Code Playgroud)

因为Foo's m_value是私有的(我想保持这种方式),我想我会将该SetValue函数声明为Foo该类的朋友,以便它可以在需要时访问静态成员.

我在Foo公共区域内尝试过这些方面的声明:

template<class X, class Y> friend void Blarg<X, Y>::SetValue(double _val);

template<class X, class Y> friend void Blarg::SetValue(double _val);

friend void Blarg::SetValue(double _val);
Run Code Online (Sandbox Code Playgroud)

......但编译没有运气.如果可能,这个的正确语法是什么?

Jan*_*rny 7

你必须在Blarg课前定义类Foo,以便将其中一个Blarg方法标记为friend.确定在使用好友行声明Blarg之前定义(或包含)Foo

  • 那并修复了成员函数的类型(缺少返回类型).+1 (2认同)