C++初级学习的一些实例代码<谭浩强版C++>
参考文档:C++学习总结
<>
<>
<枚举类型与switch语句>
#include <iostream>
using namespace std;
void main()
{
enum {red,blue,yellow,black};
int se;
cin>>se;
switch(se)
{
case red:cout<<"red.";break;
case blue:cout<<"blue.";break;
case yellow:cout<<"yellow.";break;
case black:cout<<"black.";break;
default :cout<<"have no ideal.";break;
}
system("pause");
}
<延时程序>
void main()
{
cout<<"Enter the delay time,in seconds:";
float secs;
cin>>secs;
clock_t delay=secs*CLOCKS_PER_SEC;//CLOCKS_PER_SEC等于每秒钟包含的系统时间单位数
cout<<"starting\a\n";
clock_t start=clock(); //clock_t作为clock()返回类型,根据系统不同,可能是long、usigned long等
while(clock()-start<delay)
;
cout<<"done!\a\n";
system("pause");
}
<类模板——int/float/char型比较>
#include <iostream>
using namespace std;
template <class numtype>
class Compare
{
public:
Compare(numtype a,numtype b){x=a;y=b;}
numtype max(){return (x>y)?x:y;}
numtype min(){return (x<y)?x:y;}
private:
numtype x,y;
};
void main()
{
Compare <int>cmp1(4,5);//使用类模板时,对象的定义方式与一般对象略有不同
Compare <double>cmp2(23,56,43.72);
Compare <char>cmp3('a','A');
cout<<cmp1.max()<<"is the Maximum of two INTEGER number."<<endl;
cout<<cmp1.min()<<"is the Minimum of two INTEGER number."<<endl;
cout<<cmp2.max()<<"is the Maximum of two DOUBLE number."<<endl;
cout<<cmp2.min()<<"is theMinimum of two DOUBLE number."<<endl;
cout<<cmp3.max()<<"is the Maximum of two CHAR number."<<endl;
cout<<cmp3.min()<<"is the Maximum of twoCHAR number."<<endl;
}
<运算符重载——复数相加>
【运算符重载作为类的成员函数】
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(double r=0,double i=0){real=r;imag=i;cout<<"object set"<<endl;};
Complex operator+(Complex &c2);//运算符重载
~Complex(){cout<<"object free"<<endl;};
void display();
private:
double real;
double imag;
};
Complex Complex::operator+(Complex &c2)//返回值为对象
{
Complex c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
void main()
{
Complex c1(3,4),c2(5,-10),c3;
c3=c1+c2;//运算符重载
cout<<" c1=";c1.display();
cout<<" c2=";c2.display();
cout<<" c1+c2=";c3.display();
}
【运算符重载作为友元函数时,程序的一些修改】
class Complex
{
public:
Complex(double r=0,double i=0){real=r;imag=i;cout<<"object set"<<endl;};
friend Complex operator+(Complex &c1,Complex &c2);//运算符重载
~Complex(){cout<<"object free"<<endl;};
void display();
private:
double real;
double imag;
};
Complex operator+(Complex &c1,Complex &c2)
{
Complex c;
c.real=c1.real+c2.real;
c.imag=c1.imag+c2.imag;
return c;
}
<运算符重载——">>/<<">
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(double r=0,double i=0):real(r),imag(i){};//参数列表初始化构造函数
friend ostream & operator <<(ostream &,Complex &);//作为友元函数声明重载运算符"<<"
friend istream & operator >>(istream &,Complex &);//作为友元函数声明重载运算符">>"
private:
double real;
double imag;
};
ostream & operator <<(ostream &output,Complex &c)
{
output<<"("<<c.real;
if(c.imag>=0)
output<<"+";
output<<c.imag<<"i)";
return output;
}
istream & operator>>(istream &input,Complex &c)
{
cout<<"input real part and imaginary part of complex number:";
input>>c.real>>c.imag;
return input;
}
void main()
{
Complex c1,c2;
cin>>c1>>c2;
cout<<"c1="<<c1<<endl;
cout<<"c2="<<c2<<endl;
}
<派生类构造函数对基类、对象、和派生类成员初始化>
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
Student(int n,string nam);
void display();
protected:
int num;
string name;
};
class Student1:public Student
{
public:
Student1(int,string,int,string,int,string);
void show();
void show_monitor();
private:
Student monitor;//定义了一个基类子对象
int age;
string addr;
};
Student::Student(int n,string nam):num(n),name(nam){};
void Student::display()
{
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
}
Student1::Student1(int n,string nam,int n1,string nam1,int a,string ad):Student(n,nam),monitor(n1,nam1),age(a),addr(ad){};
void Student1::show()
{
cout<<"This student is :"<<endl;
display();
cout<<"age:"<<age<<endl;
cout<<"address:"<<addr<<endl;
}
void Student1::show_monitor()
{
cout<<"Class monitor is :"<<endl;
monitor.display();
}
void main()
{
Student1 stud1(10010,"Wang_Ning",10001,"Li_sun",19,"115Beijing Road.Shanghai");
stud1.show();
stud1.show_monitor();
}
【多层继承派生类的构造函数初始化】
*class Student{};*class Student1:public Student{};
*class Student2:public Student1{};
Student::Student(int num,string name);
Student1::Student1(int n,string name,int a):Student(n,nam){};
Student2::Student2(int n,string nam,int a,int s):Student1(n,nam,a){};
<多重继承中的虚基类>
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person(string nam,char s,int a):name(nam),sex(s),age(a){};
protected:
string name;
char sex;
int age;
};
class Teacher:virtual public Person
{
public:
Teacher(string nam,char s,int a,string t):Person(nam,s,a),title(t){};
protected:
string title;
};
class Student:virtual public Person
{
public:
Student(string nam,char s,int a,float sco):Person(nam,s,a),score(sco){};
protected:
float score;
};
class Graduate:public Teacher,public Student
{
public:
//构造函数要对Person类初始化
Graduate(string nam,int a,char s,string t,float sco,float w):Person(nam,s,a),Teacher(nam,s,a,t),Student(nam,s,a,sco),wage(w){};
void Graduate::show()
{
cout<<"name:"<<name<<endl;
cout<<"age:"<<age<<endl;
cout<<"sex:"<<sex<<endl;
cout<<"score:"<<score<<endl;
cout<<"title:"<<title<<endl;
cout<<"wage:"<<wage<<endl;
}
private:
float wage;
};
void main()
{
Graduate grad1("Wang-li",24,'f',"assistant",89.5,1234.5);
grad1.show();
}
<多态性——静态多态性+动态多态性+纯虚函数+抽象类>
#include <iostream>
using namespace std;
class Shape //声明抽象基类
{
public:
virtual float area()const=0;
virtual void shapeName()const=0;
};
class Point:public Shape
{
public:
Point(float,float);
void setPoint(float,float);
float getX()const{return x;}
float getY()const{return y;}
friend ostream & operator <<(ostream &,const Point &);
virtual float area()const {return 0;}; //必须要有,否则编译报错
virtual void shapeName()const{cout<<"Point:";}; //对虚函数进行在定义
protected:
float x;
float y;
};
class Circle:public Point
{
public:
Circle(float,float,float);
void setRadius(float);
float getRadius()const;
virtual float area()const;
friend ostream &operator<<(ostream &,const Circle &);
virtual void shapeName()const{cout<<"Circle:";}; //对虚函数进行在定义
protected:
float radius;
};
class Cylinder:public Circle
{
public:
Cylinder(float,float,float,float);
void setHeight(float); //不能声明成const类型,会报错
float getHeight()const;
virtual float area()const;
float volume()const;
friend ostream &operator <<(ostream &,const Cylinder &);
virtual void shapeName()const{cout<<"Cylinder:";}; //对虚函数进行在定义
private:
float height;
};
Point::Point(float a=1,float b=1):x(a),y(b){};
void Point::setPoint(float a,float b)
{
x=a;
y=b;
}
ostream & operator <<(ostream &output,const Point &p)
{
output<<"center=["<<p.x<<","<<p.y<<"]"<<endl;
return output;
}
Circle::Circle(float a=1,float b=1,float r=1):Point(a,b),radius(r){};
void Circle::setRadius(float r)
{
radius=r;
}
float Circle::getRadius()const{return radius;}
float Circle::area()const
{
return 3.1415*radius*radius;
}
ostream &operator <<(ostream &output,const Circle &c)
{
output<<"Center=["<<c.x<<","<<c.y<<"],r="<<c.radius<<",area="<<c.area()<<endl;
return output;
}
Cylinder::Cylinder(float a,float b,float r,float h):Circle(a,b,r),height(h){};
void Cylinder::setHeight(float h)
{
height=h;
}
float Cylinder::getHeight()const
{
return height;
}
float Cylinder::area()const
{
return 2*3.1415*Circle::area()+2*3.1415*radius*height;
}
float Cylinder::volume()const
{
return Circle::area()*height;
}
ostream &operator <<(ostream &output,const Cylinder &cy)
{
output<<"center=["<<cy.x<<","<<cy.y<<"],r="<<cy.radius<<",h="<<cy.height<<",area="<<cy.area()<<",volume="<<cy.volume()<<endl;
return output;
}
void main()
{
Point point(3.2,4.5);
Circle circle(2.4,1.2,5.6);
Cylinder cylinder(3.5,6.4,5.2,10.5);
point.shapeName(); //指定类名调用成员函数
cout<<point<<endl;
circle.shapeName(); //指定类名调用成员函数
cout<<circle<<endl;
cylinder.shapeName(); //指定类名调用成员函数
cout<<cylinder<<endl<<endl;
Shape *pt;
pt=&point;
pt->shapeName(); //利用基类指针调用成员函数
cout<<point<<endl;
pt=&circle;
pt->shapeName(); //利用基类指针调用成员函数
cout<<circle<<endl;
pt=&cylinder;
pt->shapeName(); //利用基类指针调用成员函数
cout<<cylinder<<endl;
Point *pt;
pt=&cylinder;
pt->shapeName();
cout<<*pt<<endl; //利用基类指针实现运算符重载会有局限性,不能显示运算符中派生类增加的数据成员
}
<多态性——基类与派生类的成员函数调用>
【函数重载——函数名相同,但形参个数、形参类型不同】
【指定基类名调用同名函数——函数名、形参个数、形参类型相同时,有局限性】
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
Student(int,string,float);
void display();
protected:
int num;
string name;
float score;
};
class Graduate:public Student
{
public:
Graduate(int,string,float,float);
void display();
private:
float pay;
};
Student::Student(int n,string nam,float s):num(n),name(nam),score(s){};
void Student::display()
{
cout<<"num:"<<num<<",name:"<<name<<",score:"<<score<<endl;
}
Graduate::Graduate(int n,string nam,float s,float p):Student(n,nam,s),pay(p){};
void Graduate::display()
{
cout<<"num:"<<num<<",name:"<<name<<",score:"<<score<<",pay:"<<pay<<endl;
}
void main()
{
//Student stud1(1001,"Li",87.5);
Graduate grad1(2001,"Wang",98.5,7800);
//stud1.display();
grad1.Student::display();
grad1.Graduate::display();//只能输出派生类中未增加的基类成员
}
【利用基类指针或引用——函数名、形参个数、形参类型相同时,有局限性】
#include <iostream>
. . .
void main()
{
Graduate grad1(2001,"Wang",98.5,7800);
Student *p_Stu;
p_Stu=&grad1;
p_Stu->display();//派生类对象地址赋值给指向基类的指针,输出的数据不能使派生类增加的;
Graduate *p_Gra;
p_Gra=&grad1;
p_Gra->display();//派生类对象地址赋值给指向派生类的指针;
}
【利用基类指针或引+虚函数——函数名、形参个数、形参类型相同时】
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
Student(int,string,float);
virtual void display();//声明display函数为虚函数
protected:
int num;
string name;
float score;
};
class Graduate:public Student
{
public:
Graduate(int,string,float,float);
void display();
private:
float pay;
};
Student::Student(int n,string nam,float s):num(n),name(nam),score(s){};
void Student::display()
{
cout<<"num:"<<num<<",name:"<<name<<",score:"<<score<<endl;
}
Graduate::Graduate(int n,string nam,float s,float p):Student(n,nam,s),pay(p){};
void Graduate::display()
{
cout<<"num:"<<num<<",name:"<<name<<",score:"<<score<<",pay:"<<pay<<endl;
}
void main()
{
Graduate grad1(2001,"Wang",98.5,7800);
Student *p_Stu;
p_Stu=&grad1;
p_Stu->display();//派生类对象地址赋值给指向基类的指针,派生类增加的数据也输出
Graduate *p_Gra;
p_Gra=&grad1;
p_Gra->display();
}
<指向基类指针与指向派生类指针调用派生类的不同>
#include <iostream>
using namespace std;
class Point
{
public:
Point()
{
cout<<"executing Point contructor"<<endl;
}
~Point()
{
cout<<"executing Point destructor"<<endl;
}
};
class Circle:public Point
{
public:
Circle()
{
cout<<"executing Circle contructor"<<endl;
}
~Circle()
{
cout<<"executing Circle destructor"<<endl;
}
};
void main()
{
Point *p=new Circle;
delete p;
cout<<endl;
Circle *c=new Circle;
delete c;
}
结果:
【虚析构函数】
. . .
virtual ~Point()
{
cout<<"executing Point destructor"<<endl;
}
. . .
结果:
<流文件中:peek函数+putback函数+get函数+ignore函数>
#include <iostream>
using namespace std;
void main()
{
char c[50],k;
cout<<"please enter a sentence:";
cin.get(c,50,'/'); //取49(50-1)个字符给字符数组c[50],遇到'/'时停止
cout<<"The first part is:"<<c<<endl; //可以使用"cout<<c"输出字符数组中的元素;
k=cin.peek(); //将字符指针指向的下一个字符取出给k,并且字符指针的位置不移动
cout<<"The next character is:"<<k<<endl;
cin.putback('W'); //将'W'插入到下一个cin.get流中
cin.ignore(); //忽略一个字符
cin.get(c,50,'*'); //继续在终端生取字符,关键是在putback()和ignore()函数之后
cout<<"The second part is:"<<c<<endl;
}
结果:
#include <iostream>
using namespace std;
void main()
{
char c[50],k;
cout<<"please enter a sentence:";
cin.get(c,50,'/');
cout<<"The first part is:"<<c<<endl;
k=cin.peek();
cout<<"The next character is:"<<k<<endl;
cin.ignore();
cin.putback('W');
cin.get(c,50,'*');
cout<<"The second part is:"<<c<<endl;
}
结果:
<文件流的操作>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void main()
{
ofstream outfile("../data1.dat",ios::out); //注意用双引号,相对路径为“../data.dat”
string str
if(!outfile)
{
cerr<<"open failed!"<<endl;
exit(1);
}
cout<<"enter a sentence:";
cin>>str;
outfile<<str; //输出到文件,string类型遇空格则停止读入
outfile.close();
}
【输入带空格的字符串】
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void main()
{
ofstream outfile("../data1.dat",ios::out); //注意用双引号,相对路径为“../data.dat”
char ch[100];
if(!outfile)
{
cerr<<"open failed!"<<endl;
exit(1);
}
cout<<"enter a sentence:";
outfile<<gets(ch); //输出到文件,可以读入空格,直到回车送入缓冲区
outfile.close();
}
<二进制文件读写操作与seekp函数与seekg函数>
#include <fstream>
#include <iostream>
using namespace std;
struct student
{
int num;
char name[20];
float score;
};
void main()
{
student stud[5]={1001,"Li",85,1002,"Wu",97.5,1003,"Wang",54,1004,"Tan",76.5,1005,"Ling",96};
int index;
fstream iofile("stud.dat",ios::in|ios::out|ios::binary); //由于涉及到文件的读取和写入操作,所以
if(!iofile)
{
cerr<<"open failed!"<<endl;
exit(1);
}
for(int i=0;i<5;i++)
iofile.write((char *)&stud[i],sizeof(stud[i]));
/*输出指定成员信息*/
student cc;
cout<<"the date index to be read:";
cin>>index;
iofile.seekg(index*sizeof(stud[0]),ios::beg); //将读文件指针定位到将要读的字符处
iofile.read((char *)&cc,sizeof(cc)); //二进制文件读操作
cout<<cc.num<<" "<<cc.name<<" "<<cc.score<<endl;
/*修改成员数据*/
stud[2].num=2012;
strcpy(stud[2].name,"Xu");
stud[2].score=100;
iofile.seekp(2*sizeof(stud[0]),ios::beg); //将写文件指针定位到将要修改的字符处
iofile.write((char *)&stud[2],sizeof(stud[2])); //二进制文件写操作
/*输出修改过后的所有成员数据*/
iofile.seekg(0,ios::beg); //恢复读文件指针的位置,以便read输出所有成员信息
for(int i=0;i<5;i++)
{
iofile.read((char *)&stud[i],sizeof(stud[i]));
cout<<stud[i].num<<" "<<stud[i].name<<" "<<stud[i].score<<endl;
}
iofile.close();
}
<字符串流的使用>
#include <strstream>
#include <iostream>
using namespace std;
void main()
{
char ch[50]="12 34 65 -23 -32 33 61 99 321 32";//字符数组的赋值
int a[10],i,j,temp;
istrstream strin(ch,sizeof(ch)); //将数组ch字符与字符串输入流关联
cout<<"ch:"<<ch;
for(i=0;i<10;i++)
strin>>a[i];
cout<<endl;
cout<<"a:";
for(i=0;i<10;i++)
{
cout<<a[i]<<" ";
}
for(i=0;i<10;i++)
{
for(j=i+1;j<10;j++)
{
if(a[j]>a[i])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
ostrstream strout(ch,sizeof(a)); //将数组ch字符与字符串输出流关联
for(i=0;i<10;i++)
strout<<a[i]<<" ";
cout<<endl;
cout<<"order ch:"<<ch<<endl;
system("pause");
}