这段代码中,报错 'invalid use of incomplete type 'class student'' 是因为在 Person 类的成员函数 show 中,对 student 类的成员 score 进行访问,但是在 show 函数之前,编译器并没有见过 student 类的定义,因此无法识别 student 类的成员 score。

要解决这个问题,可以将 show 函数的定义放在 student 类的后面,或者在 Person 类中提前声明 student 类的存在。

方法一:将 show 函数定义放在 student 类之后

#include<iostream>
using namespace std;

class student;

class Person
{
public:
    Person(string newname)
    {
        this->name = newname;
    }
    void show(student &a);
private:
    string name;
};

class student
{
    friend void Person::show(student &a);

public:
    student(int newscore)
    {
        this->score = newscore;
    }

private:
    int score;
};

void Person::show(student &a)
{
    cout << a.score << endl;
}

int main()
{
    Person p('张三');
    student P2(12);

    p.show(P2);
    return 0;
}

方法二:在 Person 类中提前声明 student 类

#include<iostream>
using namespace std;

class student;

class Person
{
public:
    Person(string newname)
    {
        this->name = newname;
    }
    void show(student &a);
private:
    string name;
};

class student
{
    friend void Person::show(student &a);

public:
    student(int newscore)
    {
        this->score = newscore;
    }

private:
    int score;
};

void Person::show(student &a)
{
    cout << a.score << endl;
}

int main()
{
    Person p('张三');
    student P2(12);

    p.show(P2);
    return 0;
}

通过以上两种方法,编译器就可以识别到 student 类的成员 score,从而消除 'invalid use of incomplete type' 错误。

C++ 类友元函数与类成员访问错误:'invalid use of incomplete type' 的解决方法

原文地址: https://www.cveoy.top/t/topic/wvb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录