虚函数、继承
好吧,真的是好久没写过这样的代码,弄得有些地方忘了......
在这里,如果要把子类“赋值”给基类,可以用指针、或者引用
#include<iostream>
#include<string>
#include<queue>
#include<vector>
#include<fstream>
using namespace std;
class Book
{
public:
Book(){}
Book &operator=(Book &p)
{
Book *ch=&p;
if(this!=&p)
{
*this=p;
}
return *this;
}
virtual ~Book(){};
//virtual ostream &operator<<(ostream &os)const=0;
virtual void display()=0;
virtual string type()=0;
virtual int gettol()=0;
virtual bool push(string s)=0;
virtual bool pop()=0;
};
class ST: public Book
{
private:
vector<string>name;
public:
ST():Book(){}
string type()
{
string st="ST book";
return st;
}
int gettol()
{
return name.size();
}
bool push(string s)
{
name.push_back(s);
return true;
}
bool pop()
{
if(name.empty()) return false;
vector<string>::iterator it=name.end()-1;
name.erase(it);
return true;
}
friend ostream &operator<<(ostream &os,ST &tmp)
{
vector<string>::iterator it=tmp.name.begin();
os<<"Type: "<<tmp.type()<<endl<<"Total: "<<tmp.name.size()<<endl;
for(;it!=tmp.name.end();it++)
os<<"Book name: "<<*it<<endl;
return os;
}
void display()
{
cout<<*this;
}
virtual ~ST(){};
};
class DZ: public Book
{
private:
vector<string>name;
public:
DZ():Book(){}
string type()
{
string st="DZ book";
return st;
}
int gettol()
{
return name.size();
}
bool push(string s)
{
name.push_back(s);
return true;
}
bool pop()
{
if(name.empty()) return false;
vector<string>::iterator it=name.end()-1;
name.erase(it);
return true;
}
friend ostream &operator<<(ostream &os,DZ &tmp)
{
vector<string>::iterator it=tmp.name.begin();
os<<"Type: "<<tmp.type()<<endl<<"Total: "<<tmp.name.size()<<endl;
for(;it!=tmp.name.end();it++)
os<<"Book name: "<<*it<<endl;
return os;
}
void display()
{
cout<<*this;
}
virtual ~DZ(){};
};
int main()
{
//Book w;
ST tmp;
DZ tmp1;
string s;
cout<<"请输入实体书籍名称,输入“exit”结束输入"<<endl;
while(cin>>s)
{
if(s=="exit") break;
tmp.push(s);
}
cout<<"请输入电子书籍名称,输入“exit”结束输入"<<endl;
while(cin>>s)
{
if(s=="exit") break;
tmp1.push(s);
}
//ST *p=&tmp;
//DZ *p1=&tmp1;
Book &w=tmp; //这里用的是引用
Book &w1=tmp1;
w.display();
w1.display();
w.pop();
w1.pop();
cout<<endl<<endl;
w.display();
w1.display();
return 0;
}
朋友们,虽然这个世界日益浮躁起来,只要能够为了当时纯粹的梦想和感动坚持努力下去,不管其它人怎么样,我们也能够保持自己的本色走下去。

浙公网安备 33010602011771号