C++ 错误 C2027: 使用未定义的类型 'second' (Friend Class)

C++ error C2027: use of undefined type 'second' (Friend Class)

我正在学习友元函数 (C++),但我不明白为什么这段代码不起作用。我明白了

error: "error C2027: use of undefined type 'second'". (line number 6)

当然只是一个例子(无用)。我正在尝试使用另一个 class 的成员函数作为朋友(只是那个函数)。我在网上找到了一些例子。但是在一个旧的 post 这里有人说另一个 class 的成员函数不能是 class 的朋友..这是真的吗?

#include<iostream>
using namespace std;
class second;

class test
{
    friend void second::fun(test &);
public:
    int j = 89;
private:
    int t = 12;
};

class second
{
public:
    void fun(test &b)
    {
        cout << "Try " << b.j << endl;
    }
    int a = 29;
private:
    int u = 10;
};

int main()
{
    test b;
    second one;
    one.fun(b);
    return 0;
}

要访问 second::fun,需要 second 的完整定义。如果您 颠倒定义这些 类 的顺序 并改为转发声明 test ,则可以解决此问题。但是同样,b.j 需要定义 test,因此您必须 分离和推迟 second::fun 的定义:

#include<iostream>
using namespace std;
class test;

class second
{
public:
    void fun(test &b); // test must be declared for using a reference to it
    int a = 29;
private:
    int u = 10;
};

class test
{
    friend void second::fun(test &); // second must be defined to access its member
public:
    int j = 89;
private:
    int t = 12;
};

void second::fun(test &b)
{
    cout << "Try " << b.j << endl;   // test must be defined to access its member
}

int main()
{
    test b;
    second one;
    one.fun(b);
    return 0;
}

尝试以下操作:

class test;

class second
{
public:
    void fun(test &b);
    int a = 29;
private:
    int u = 10;
};

class test
{
    friend void second::fun(test &);
public:
    int j = 89;
private:
    int t = 12;
};

void second::fun(test &b)
{
    cout << "Try " << b.j << endl;
}

您的代码有几个问题。对于

friend void second::fun(test &);

要工作,编译器必须知道 second 是什么。因为它是一个不完整的类型,你会得到一个编译器错误。为了解决这个问题,您需要在测试前声明 second。这样做会带来另一个问题

second::fun(test &b)

使用 test。为了解决这个问题,我们将转发声明 test,然后声明 second。更改后,您需要将实际函数定义移出 second 并将其放在 test.

之后
#include<iostream>
using namespace std;
class test;
class second
{
public:
    void fun(test &b);
    int a = 29;
private:
    int u = 10;
};
class test
{
    friend void second::fun(test &);
public:
    int j = 89;
private:
    int t = 12;
};

void second::fun(test &b)
{
    cout << "Try " << b.j << endl;
}

int main()
{
    test b;
    second one;
    one.fun(b);
    return 0;
}

Live Example

当编译器读取这一行时

friend void second::fun(test &);

不知道第class秒是否确实有数据成员fun。为确保此行正确,编译器需要 class second.

的定义

另一方面,函数fun的定义必须知道classtest有数据成员j.

解决冲突可以这样写

#include<iostream>
using namespace std;

class test;

class second
{
public:
    void fun(test &b); // class test is already declared above
    int a = 29;
private:
    int u = 10;
};

class test
{
    friend void second::fun(test &); //class second is already defined above
public:
    int j = 89;
private:
    int t = 12;
};

void second::fun(test &b)
{
    cout << "Try " << b.j << endl; // class test is already defined above
}

int main()
{
    test b;
    second one;
    one.fun(b);
    return 0;
}