13.1.2 纯虚函数(Pure Virutal Functions)
#ifndef HEADER_ACCOUNT #define HEADER_ACCOUNT #include<string> using std::string; class Account { string acntNumber; double balance; public: //构造函数 Account(string _acntNumber, double _balance=0.0); //定义一个虚函数display并定义为const型 virtual void display()const; //定义返回double类型函数getBalance double getBalance(){ return balance;} //定义void型函数,参数为double型,对balance变量进行加操作 void deposit(double amount){ balance += amount;} //定义重载运算符== //右边的参数为一个Account类型的引用a //而右边的参数当前类型自己 //如果为等于返回true否则返回falsh bool operator==(const Account& a)const{ std::cout<<"acntNumber:"<<acntNumber<<" = a.acntNumber"<<a.acntNumber<<"\n"; return balance == a.balance; } //定义一个虚函数withdrawal,一会儿进行声明纯虚函数 virtual void withdrawal(double amount); }; #endif
#include <iostream> #include "account.h" Account::Account(string _acntNumber, double _balance):acntNumber(_acntNumber),balance(_balance){}; void Account::display()const{ std::cout<<"acntNumber:"<<acntNumber<<", balance:"<<balance<<"\n"; }; void Account::withdrawal(double amount){ balance += amount; };
//我们引入抽像类(Abstract Classes)的概念,抽像类的用途是被继承
//定义抽像类就是在类定义中至少声明一个纯虚函数Virtual,
/**/
#include <iostream>
#include "account.h";
int main()
{
//定义小向
//Account *a = new Account("小向",22.11);
//a->display();
//定义小菊
//Account *b = new Account("小菊",22.11);
//b->display();
//给小向加上一百元
//a->deposit(100);
//给小菊加上十元
//b->deposit(100);
//现在对比两个人的帐户金额是否相同
//bool isok=false;
//这里并没有调用重载运算符operator==
//isok = a==b;
//a->operator==b;
//isok = a.operator==b;
//这里停一下,重载运算符调用不成功样,得先去学习一下重载运算符
Account a("小向",22.11);
Account b("小菊",22.11);
if(a == b){
std::cout<<"相等\n";
}else
std::cout<<"不相等\n";
system("pause");
return 0;
}