9

我有这样的课:

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

class Foo : public Bar {    
  // ...
  static double m_value;
  // ...    
}; 

还有一个是这样的:

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

由于Foo'sm_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);

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

4

3 回答 3

7

您必须在Blargclass 之前定义 class才能将's 方法Foo之一标记为. 确定在使用朋友行声明之前已定义(或包含) ?BlargfriendBlargFoo

于 2013-07-30T14:35:56.953 回答
3

这似乎对我有用:

template<class X, class Y>
class Blarg : public Bar {
    public:
        void SetValue(double _val);
};

class Foo : public Bar {
    private:
        static double m_value;

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

template <class X, class Y>
void Blarg<X,Y>::SetValue(double _val)
{
    Foo::m_value = _val;
}

我必须通过首先定义 Blarg 并使 SetValue 不是内联来打破循环依赖。您的朋友声明非常正确,除了缺少返回值。

于 2013-07-30T14:54:48.760 回答
0

这是正确的语法:

template<class T>
class Bla
{
 public:
  void toto(double val);
};    

class Foo {
  static double m_value;
  template<typename T>
  friend void Bla<T>::toto (double);
} ;

另外,请确保BlaFoo.

于 2013-07-30T14:47:49.587 回答