开发者

Class member attributes error

开发者 https://www.devze.com 2023-03-05 17:46 出处:网络
I have two classes and want to have a reference from class Kunde to class Konto and backward, but my compiler shows many errors. I don\'t know what the problem is. Please help me.

I have two classes and want to have a reference from class Kunde to class Konto and backward, but my compiler shows many errors. I don't know what the problem is. Please help me.

Class Konto:

#pragma once
#include "Kunde.h"

class Konto {
private:
    Kunde* kunde;
protected:
    int kontonummer;
    double stand;
public:
    int getKontonummer();
    Kunde* getKunde();
    double getKontostand();
    bool einzahlen(double betrag);
    virtual bool auszahlen(double betrag);
};

Class Kunde:

#pragma once
#include "Konto.h"
#include <string>

class Kunde {
private:
    string vorname;
    string nachname;
    Konto* konto;
public:
    Kunde(string vorname, string nachname);
    void setKonto(Konto* konto);
    Konto* getKonto();
};

I get following compiler errrors:

konto.h(6): error C2143: syntax error: missing ';' before '*'

konto.h(6): error C4430: missing typespecifier - int assumed. Note: C++ does not support "default-int"

konto.h(6): error C4430: missing typespecif开发者_如何学运维ier - int assumed. Note: C++ does not support "default-int"

and some more.


The header files can't include each other. Instead of the #includes, try a forward declaration in one or both, like this:

class Kunde;


You have a circular inclusion problem. You see the #pragma once statement in the first line of the header file? This prevents an inclusion of the header if it has already been included. Since your header files include each other, at the declaration of either Kunde or Konto the other one has not yet been defined.

You can circumvent the problem if you make a simple forward declaration of either class in the other header file. Specifically:

(Konto.h)

#pragma once

// Do NOT include Kunde.h

class Kunde;

class Konto {
    // your further class definition as normal.

The only thing is that you now should include Kunde.h in the Konto.cpp, or else this would lead to a linker error.

EDIT: see comments :) thanks


Including one file in another that includes the first file, that includes the second file that includes the first file...

surely will confuse #pragma once


Konto is including Kunde.h and Kunde is including Konto.h. Do a forward declaration in both cases


This is a classic circular dependency. You can handle it a couple ways. The first is to use forward declarations for the other class you are trying to reference. You'll need to remove the include for the other class too.

class Konto;

class Kunde { Konto* konto; ... };

The other way is to abstract out an interface that gives you what you want. I can go into further detail on that approach if you like.

0

精彩评论

暂无评论...
验证码 换一张
取 消