带好友功能的前向声明:无效使用不完整类型 [英] Forward declaration with friend function: invalid use of incomplete type

查看:92
本文介绍了带好友功能的前向声明:无效使用不完整类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>

class B;

class A{
 int a;
public:
 friend void B::frndA();
};

class B{
 int b;
public:
 void frndA();
};

void B::frndA(){
 A obj;
 std::cout << "A.a = " << obj.a << std::endl;
}

int main() {
 return 0;
}

在尝试编译此代码时,发生了一些错误.例如

When trying to compile this code, some errors occurred. E.g.

无效使用不完整的类型

invalid use of incomplete type

这段代码有什么问题?

推荐答案

将整个class B ...声明放在class A之前.您尚未声明B::frndA();.

Place the whole of the class B ... declaration before class A. You haven't declared B::frndA(); yet.

#include <iostream>
using namespace std;

class B{
    int b;
public:
    void frndA();
};

class A{
    int a;
public:
    friend void B::frndA();
};



void B::frndA(){
    A obj;
    //cout<<"A.a = "<<obj.a<<endl;
}

int main() {
    return 0;
}

这篇关于带好友功能的前向声明:无效使用不完整类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆