c++ - 不同文件中的 C++ 类继承
问题描述
我正在尝试学习 C++ 中的继承机制,我已经制作了一个 Bancnote(Bills) 类,并且我想制作一个类 Card,它继承了 Class Bancnote 中的所有函数和变量。
我得到这种类型的错误:
include\Card.h|6|error: expected class-name before '{' token|
钞票.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
纸币
#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;
}
卡片.H
#ifndef CARD_H
#define CARD_H
#include "Bancnote.h"
class Card: public Bancnote
{
public:
Card();
virtual ~Card();
protected:
private:
};
#endif // CARD_H
解决方案
你搞砸了包含。你所拥有的或多或少是这样的:
Bancnote.h:
#ifndef BANCNOTE_H
#define BANCNOTE_H
#include "Card.h" // remove this
struct Bancnote {};
#endif
卡片.h
#ifndef CARD_H
#define CARD_H
#include "Bancnote.h"
struct Card : Bancnote {}; // Bancnote is not yet declared
// when compiler reaches here
#endif
在 main 中包含时,Bancnote.h
此标头包含Card.h
,因此您尝试在声明Card
之前Bancnote
声明。实际上Bancnote
不需要 的定义Card
,因此只需删除 include 即可修复它。
PS:还有其他问题(请参阅问题下方的评论)。最重要的是,不清楚为什么 aCard
是 a Bancnote
。其次,永远不要using namespace std;
在标题中放置一个内部!(看这里为什么)
推荐阅读
- json - postgresql UPDATE 从 JSONB 数据类型中删除键/值
- delphi - “Samples\Object Pascal\Database\EMS\FireDACResource”示例如何工作?
- python-3.x - 根据日期的 where 子句查询 BigQuery
- c# - DbContext.SaveChangesAsync 的进展
- python - 如果@ in password 无法连接到Mysql
- rust - 如何复制不同类型但具有相同字段的结构类型(不是值)
- call - 使用记录方法调用记录应用程序,它在调用时启动,但应用程序实际上在没有记录方法的情况下开始工作
- c# - 以编程方式启用启动应用程序
- postgresql - 更新迁移后序列化种子数据
- c# - 如何在热敏打印机中打印二维码