【问题标题】:Why i get error class undefined when declare friend funcion with class in multi file?为什么在多文件中使用类声明友元函数时出现错误类未定义?
【发布时间】:2019-10-02 16:05:51
【问题描述】:

我在 Nhanvien 类中创建了一个朋友函数“display”(List 类的成员)。List 已声明,但它仍然保留此错误:

C2027 use of undefined type 'List'.

我正在使用 Visual Studio。我该如何解决?请帮我。对不起我的英语不好:

这是我的来源:

*//List.h*
#pragma once

#include"Nhanvien.h"

class Nhanvien;

class List
{

        Nhanvien* p;

   public:

       List();
       List(int);
       ~List();
       void display(int);
};


*//Nhanvien.h*
  
#pragma once
#include<iostream>
#include "Date.h"
#include"List.h"

class List;
class Nhanvien
{

private:
    
    char maNV[100];
    std::string tenNV;
    Date ngay;
    bool gioitinh;
    double luong;
    
public:
    
    Nhanvien();
    Nhanvien(const Nhanvien&);
    ~Nhanvien();
    void set();
    void show();
    static int count;
    friend void List::display(int);
};

show error

【问题讨论】:

    标签: c++ class header friend-function


    【解决方案1】:

    你有一个头文件的递归依赖。

    //List.h

    #pragma once
    
    #include"Nhanvien.h"
    
    //...
    

    //Nhanvien.h

    #pragma once
    #include<iostream>
    #include "Date.h"
    #include"List.h"
    //...
    

    所以标题List.h首先包含标题Nhanvien.h,而这个标题还没有看到类List的声明。

    【讨论】:

    • 这里的解决方法是去掉List.h中的include,Nhanvien的前向声明就足够了。 Nhanvien.h 中的前向声明 List 也是不必要的。
    • 它有效!非常感谢你的帮助。我花了很多时间来解决,但你做到了
    猜你喜欢
    • 2020-08-07
    • 1970-01-01
    • 2020-04-27
    • 2012-07-12
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多