首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

继承和多态有关问题

2012-02-16 
继承和多态问题//string.h(头文件)#ifndefHEADER_SAVINGS#defineHEADER_SAVINGS#includestringusingstd:

继承和多态问题
//string.h(头文件)
#ifndef   HEADER_SAVINGS
#define   HEADER_SAVINGS
#include   <string>
using   std::string;
class   Savings{
public:
double   balance;
string   acntNumber;

Savings(string   acntNo,double   balan=0.0):balance(balan),acntNumber(acntNo){}
void   depsit(double   amount){balance+=amount;}
double   getBalan()const{return   balance;}
virtual   void   display()const;
virtual   void   withdrawal(double   amount);
};
#endif


//checking_sub.h   头文件
#ifndef   HEADER_CHECKING
#define   HEADER_CHECKING
#include "saving.h "
#include   <string>
using   std::string;
enum   REMIT{remitByPost,remitByCable,other};//信汇,电汇,无
class   Checking:   public   Savings{

REMIT   remittance;
public:
Checking(string   acntNo,double   balan=0.0);
void   display()   const;
void   withdrawal(double   amount);
void   setRemit(REMIT   re){remittance=re;}
};
#endif


cpp文件!!
#include   <iostream>
#include "checking_sub.h "
#include "saving.h "
Checking::Checking(string   acntNo,double   balan):Savings(acntNo,balan),remittance(other){}
void   Checking::display()const{
std::cout < < "Checking   Account: "+acntNumber+ "= " < <balance < < "\n ";
}
void   Checking::withdrawal(double   amount){

if(remittance==remitByPost)
amount+=30;
else   if(remittance==remitByCable)
amount+=60;
Savings::withdrawal(amount);
}
int   main()
{
system( "pause ");
return   0;
}

///////////////////////////
正在编译...
savings.cpp
正在链接...
savings.obj   :   error   LNK2001:   无法解析的外部符号   "public:   virtual   void   __thiscall   Savings::display(void)const   "   (?display@Savings@@UBEXXZ)
savings.obj   :   error   LNK2001:   无法解析的外部符号   "public:   virtual   void   __thiscall   Savings::withdrawal(double) "   (?withdrawal@Savings@@UAEXN@Z)
F:\sort\sort\Debug\sort.exe   :   fatal   error   LNK1120:   2   个无法解析的外部命令
生成日志保存在“file://f:\sort\sort\sort\Debug\BuildLog.htm”
sort   -   3   个错误,0   个警告
==========   生成:   0   已成功,   1   已失败,   0   最新,   0   已跳过   ==========
这是编译问题!

希望给个方法把继承和多态都体现出来!
谢谢!



[解决办法]
virtual void Savings::display() const和virtual void Savings::withdrawal(double amount)的函数体呢?

[解决办法]
Savings如果要作为 抽象类,可以把display withdrawal这两个函数声明成纯虚函数。如果不想就写一个实现
[解决办法]
需要基类的2个虚函数的函数体。
[解决办法]
在 main函数里面 ,如果 display是虚函数 ,Checking这个类重写了这个函数 那么 :

Savings * check = new Checking( "123 ");
check-> display(); // 这里会调用 Checking类 里面的 display函数,这就是多态的体现 ,

,记得 要在 Savings.cpp里面 实现 savings 的 display和 withdrawal函数 ,否则 必须把这两个函数声明为 纯虚函数 .要不就会出现链接出错

热点排行