【问题标题】:in c++, how to friend a static function from another class在 C++ 中,如何从另一个类中获取静态函数
【发布时间】:2014-05-09 19:40:59
【问题描述】:

我想要两个类,A和B。B类中有一个静态函数,A想给这个函数加好友。

我的代码如下

A 类

#ifndef A_H_
#define A_H_
#include "B.h"

static void B::staticFunction();

class A {
public:

    friend static void B::staticFunction();
    A();
    virtual ~A();
};

#endif /* A_H_ */

B类

#ifndef B_H_
#define B_H_
#include "A.h"

class B {
public:
    static void staticFunction();
    B();
    virtual ~B();
}; 

#endif /* B_H_ */

但是编译器告诉我:

不能声明成员函数 'static void B::staticFunction()' 具有静态链接 [-fpermissive]

'static void B::staticFunction()' 在类之外的声明不是定义 [-fpermissive]

我应该怎么做才能修复这些错误?提前感谢您帮助我

编辑

谢谢大家,终于明白了

工作代码是

class A;
class B{
public:
    static void staticFunction(A* a);
};

class A {
public:
friend void B::staticFunction(A* a);
    A();
    virtual ~A();
private:
    int i;
};

【问题讨论】:

  • 在朋友声明中省略返回类型,错误的前向声明,它应该可以工作。另外,递归包含两个标题?请把它删掉。

标签: c++ static-methods friend-function


【解决方案1】:

最简单的例子如下:

struct A {
    static int doit();
};

class B {
    static int i;
    friend int A::doit();
};

int B::i = 0;

int A::doit()
{
    return ++B::i;
}

这里的顺序很重要:您首先需要定义包含其他类将成为朋友的静态函数的类。由于显而易见的原因,该函数的定义需要延迟到两个类都定义完毕。

您可能希望查找 the different meanings of static in c++,因为您将非成员函数 static 与内部链接 static 混合在一起。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 2012-03-18
    • 2014-07-13
    • 1970-01-01
    • 2016-02-06
    • 1970-01-01
    相关资源
    最近更新 更多