Circular Dependency! object creation

0

The Code is very simple! I have two classes student.h and diciplina.h and I need to maintain a circular dependency between them!

When I'm in student.h I can create an attribute of class discipline use new, constructor, sets and gets. But when I do, I can create and set to 0 but n can give a new one and use: /

[Error] forward declaration of 'class discipline: student' and
[Error] invalid use of incomplete type 'class diciplina :: student'

You're already grateful!

#ifndef DICIPLINA_H
#define DICIPLINA_H

#include <string>
using namespace std;
#include "aluno.h"

#define MAX 20


class aluno;

class diciplina{

    public:

    class aluno;

    diciplina(string codDic,    string descricaoDisc){  

    this->codDic = codDic;
    this->descricaoDisc = descricaoDisc;

    for(int i = 0; i<20; i++) // Inicializa com tudo 0
    dA[i] = 0;  
    }

    ~diciplina(){

    delete[]dA;

    }   
    bool matricula(aluno **al,int id){

    for(int i = 0; i<10; i++)
    if(dA[i] == 0){
    dA[i] = new aluno("Fulano","09834534","Computer Science"); //  ESSA LINHA QUE DA ERRO
    return true;
    system("pause");
    }
    return false;   
    }

    private:
    string codDic;
    string descricaoDisc;
    aluno *dA[MAX];


    };  
#endif

    #ifndef ALUNO_H
#define ALUNO_H
#include <string>
#include <iostream>
#include "diciplina.h"

using namespace std;

class diciplina; // declaracação forward

class aluno
{
    public:

        aluno(string nome, string cpf, string curso){
        this->nome = nome;
        this->cpf = cpf;
        this->curso = curso;    

        for(int i = 0; i<10; i++)
        alunoDiciplinas[i] = 0;
        }
        ~aluno(){       

        delete[] alunoDiciplinas;

        }

        bool matricula(diciplina **dic,int id){

        for(int i = 0; i<10; i++)
        if(alunoDiciplinas[i] == 0){
        alunoDiciplinas[i] = new diciplina(dic[id]->getCod(),dic[id]-   >getDiciplina()); // MAS AQUI NÃO DA ERRO !!
        return true;
        }
        return false;
    }



        private:        
        string nome, cpf, curso;
        diciplina *alunoDiciplinas[10];

};
#endif
    
asked by anonymous 22.04.2016 / 02:53

1 answer

0

Well, the problem is that you use the aluno class before it is defined (implemented), and it does not happen with the diciplina class because you already set it when you used it in aluno . This happens because it is out of the C ++ standard, and the compiler does not accept it.


Solution
Well, I do not know if it is the best, but following the C ++ standard and from what I understand of your code (that it is separated in% with% and% with%), leave in aluno.h only the signature of the methods, and its respective implementations in diciplina.h files. This way, all statements are made before their implementations, the compiler knows how to work with it and then it accepts.

    
22.04.2016 / 03:55