Circular Dependency! object creation

Asked

Viewed 204 times

0

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

when I’m a student. h I can create an attribute of the dicipline class use new, constructor, sets, and gets. But when I do and set to 0 but n I can give a new and use :/

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

Thank you from now on!

#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

1 answer

0


Well, the problem is that you use the class aluno before it is defined (implemented) and the same does not apply to the class diciplina because you already defined it when you were using it in aluno. This happens because it is outside the standard of C++, and then the compiler does not accept.


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.