C++基础教程(总结)(四)
凡是包含纯虚函数的类都是抽象类,抽象基类是本类族的公共接口
多态性与虚函数源代码:
复制代码
#include
#include
using namespace std;
?
class Student
{
public:
? ? Student(string nam,int a,char s,float sco):name(nam),age(a),sex(s),score(sco)
? ? {
? ? }
? ??
// ? ?virtual void display() = 0;//纯虚函数
? ? virtual void display()//虚函数
? ? {
? ? ? ? cout<<"name:" <<'\t'<
? ? ? ? ? ? <<"age:" ?<<'\t'<
? ? ? ? ? ? <<"sex:" ?<<'\t'<
? ? ? ? ? ? <<"score:"<<'\t'<
? ? }
protected:
? ? string name;
? ? int age;
? ? char sex;
? ? float score;
};
?
class Graduate:public Student
{
public:
? ? Graduate(string nam,int a,char s,float sco,float w):
? ? ? Student(nam,a,s,sco),wage(w)
? ? ?{
? ? ?}
? ? ?void display()//虚函数
? ? ?{
? ? ? ? cout<<"name:" <<'\t'<
? ? ? ? ? ? <<"age:" ?<<'\t'<
? ? ? ? ? ? <<"sex:" ?<<'\t'<
? ? ? ? ? ? <<"score:"<<'\t'<
? ? ? ? ? ? <<"wage:" <<'\t'<
? ? ?}
private:
? ? float wage;
};
?
?
int main()
{
? ? Student ?stud("LiGang",18,'m',95);
? ? Graduate grad("WangLi",24,'f',99.5,1325.5);
? ??
? ? grad.display();//静态关联
? ? cout<<"******************************************\n";
?
? ? Student *pt = &stud;
? ? pt->display();//动态关联
? ??
? ? cout<<"******************************************\n";
? ??
? ? pt = &grad;
? ? pt->display();
? ??
? ? return 0;
}
复制代码
17、输入输出流
?
标准I/O:键盘输入数据,显示到屏幕上
文件I/O:以外存磁盘文件为输入输出对象
字符串I/O:对内存中指定的空间(通常为字符数组,利用该空间可存储任何信息)进行输入输出
标准输入输出:
标准输出流
cout,cerr,clog流
格式输出
使用控制符控制输出格式:头文件iomanip
使用流对象的成员函数:格式标志在类ios中被定义为枚举值
用流成员函数put输出字符
标准输入流
cin流
用流成员函数输入字符:无参、1个、3个参数的get,getline
Istream类的其他成员函数
18、用typedef声明类型
?
?
19、预处理命令
?
?
?
typedef与预处理命令源代码:
?
复制代码
#include
using namespace std;
?
typedef int ARR[2]; //用typedef声明数组类型
?
#define MAX(x,y) x>y?x:y ?//带参数的宏定义
?
int main()
{
? ? int max;
? ? ARR a;
? ? a[0]=1;
? ? a[1]=2;
? ? max=MAX(a[0],a[1]);
#ifdef MAX