Search code examples
c++classheaderfriend-function

Why i get error class undefined when declare friend funcion with class in multi file?


I created a friend funcion "display"(member of List class) in Nhanvien class.List was declared but it still keep this error:

C2027 use of undefined type 'List'.

I'm using Visual studio. How can i fix it?? Please help me. Sorry for my bad English :<

here is my source:

*//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


Solution

  • You have a recursive dependency of headers.

    //List.h

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

    //Nhanvien.h

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

    So the header List.h includes at first the header Nhanvien.h and this header does not see yet the declaration of the class List.