不同文件中的C ++类继承

时间:2019-01-11 10:10:17

标签: c++ inheritance

我正在尝试学习C ++中的继承机制,我制作了一个Bancnote(Bills)类,并且想要制作一个继承了Bancnote类的所有函数和变量的Card类。

我得到这种类型的错误:

include\Card.h|6|error: expected class-name before '{' token|

BANCNOTE.H

   #ifndef BANCNOTE_H
#define BANCNOTE_H
#include <iostream>

#include "Card.h"
using namespace std;

class Bancnote
{
    public:
        Bancnote();
        Bancnote(string, int ,int ,int );
        ~Bancnote( );
        int getsumacash( );
        void setsumacash( int );
        int getsumaplata( );
        void setsumaplata( int );
        int getrest( );
        void setrest( int );
        string getnume( );
        void setnume( string );
        void ToString();


    protected:

    private:
        string nume;
        int sumacash;
        int rest;
        static int sumaplata;


};

#endif // BANCNOTE_H

BANCNOTE.CPP

#include <iostream>
#include "Bancnote.h"
#include "Card.h"
using namespace std;
int Bancnote::sumaplata=0;

Bancnote::Bancnote(string _nume,int _sumacash,int _rest, int _sumaplata )
{
    this->nume=_nume;
    this->sumacash=_sumacash;
    this->rest=_rest;
    this->sumaplata=_sumaplata;
}

Bancnote::Bancnote()
{
    this->nume="";
    this->sumacash=0;
    this->rest=0;
    this->sumaplata=0;
}

Bancnote::~Bancnote()
{
    cout<<"Obiectul"<<"->" <<this->nume<<"<-"<<"a fost sters cu succes";
}

string Bancnote::getnume()
{
    return nume;
}
void Bancnote::setnume(string _nume)
   {
      this->nume=_nume;
   }
int Bancnote::getsumacash()
{
    return sumacash;
}
void Bancnote::setsumacash(int _sumacash)
{
    this->sumacash=_sumacash;
}
int Bancnote::getsumaplata()
{
    return sumaplata;
}
void Bancnote::setsumaplata(int _sumaplata)
{
    this->sumaplata=_sumaplata;
}
int Bancnote::getrest()
{
    return rest;
}
void Bancnote::setrest(int _rest)
{
    this->rest=_rest;
}
void Bancnote::ToString()
{
    cout<< "-----"<<getnume()<< "-----"<<endl;
    cout<<"Suma Cash: "<<this->getsumacash()<<endl;
    cout<<"Suma spre plata: "<<this->getsumaplata()<<endl;
    cout<<"Restul:"<<this->getrest()<<endl;

}

CARD.H

#ifndef CARD_H
#define CARD_H
#include "Bancnote.h"

class Card: public Bancnote
{
public:
    Card();
    virtual ~Card();

protected:

private:
};

#endif // CARD_H

1 个答案:

答案 0 :(得分:2)

您弄乱了包含项。您所拥有的或多或少是这样的:

Bancnote.h:

漢字

Card.h

#ifndef BANCNOTE_H
#define BANCNOTE_H
#include "Card.h"    // remove this

struct Bancnote {};
#endif

主要在其中包含#ifndef CARD_H #define CARD_H #include "Bancnote.h" struct Card : Bancnote {}; // Bancnote is not yet declared // when compiler reaches here #endif ,然后此标头包含Bancnote.h,因此您尝试在声明Card.h之前声明Card。实际上,Bancnote不需要Bancnote的定义,因此只需删除include即可对其进行修复。

PS:还有其他问题(请参见问题下方的评论)。最重要的是,不清楚为什么CardCard。其次,切勿将Bancnote放在标题内! (请参阅here原因)