Part 1/6 考试范围
第1章
面向对象的三大特征,类和对象,程序开发过程
第2章
cin、cout,::,全局变量,定义函数时形参带有默认值,函数重载
引用,利用指针动态内存空间管理,try catch throw机制的异常处理方式
第3章
类的定义,对象的定义,this指针,构造函数,复制构造函数,析构函数,对象数组,对象指针、对象引用、对象参数
第4章
对象成员,常数据成员,常对象,常成员函数,友元函数、友元成员、友元类
第5章
类的继承与派生,private、protected、public,定义派生类对象时,构造函数的调用顺序,同名冲突,赋值兼容的四种情况
第6章
静态多态性、动态多态性,运算符重载,友元重载,成员函数重载,输入/输出流重载:ostream & 和 istream &,虚函数的定义,纯虚函数和抽象类
第7章
函数模板的定义及调用,函数模板的重载,类模板的定义及调用
第8章
文件的分类,open打开方文件,ios::in 读文件, ios::out 写文件,close关闭文件
运算符>>和<<对文件操作,get、put函数,read、write函数
Part 2/6 考试真题
Part 3/6 练习题库
第1章 C++语言概述
- 课后习题
①面向对象语言:C++,Java,Python
②类是类型,对象是类类型变量,类型不占有内存,变量占有内存
③面向对象特征:封装性,继承性,多态性
④对象是是类类型变量,不是结构体变量
第2章 对C的改进及扩展
- 课后习题
①int y[n];中n必须为常量,int *py=new int[n];中n可以为常量和变量
②int add(int x,int y=4,int z=5);默认值的函数原型声明从右往左
③重载函数满足,形参的个数或类型或顺序不同
int a(int x);和int a(float x);
int b(int x,char *s);和int b(char *s,int x);
int c(int x);和int c(int x,int y);
而int d(int x); 和 char *d(int y); 不是重载
④int *p=new int;(一维数组)int *p=new int(10);(一维数组赋值)
int *p=new int[10];(10个元素)int *p=new int[10] (10);(错误语句)
⑤int x=1,y=2,&z=x;执行z=y后,x=z=y=2
- 平台习题
①全局变量 x 在main函数中可以访问,形如:“::x = 1;” 使其获得新的值1
②使用delete运算符释放所申请的动态内存空间
③为名空间ABC变量x赋值:
ABC::x = 10;
using namespace ABC; x = 10;
using ABC::x ; x = 10;
④运算符<<:
用于输出的插入符
左移位运算符
右边可以是表达式,变量
⑤关于try-catch:
语句块必须一起出现,缺一不可,且try块在先catch块在后
如果有try块,可以有多个,与try块对应的catch块可以有多个
⑥const char *;表示不能改指针,const name="abc";表示不能改name
⑦const char *ptr; 定义一个指向字符常量的指针
char const *ptr; 定义一个指向字符常量的指针
char * const; 定义一个指向字符的指针常数
⑧内联函数:
在编译时目标代码将插入每个调用该函数的地方
一般代码较短,而且调用较频繁
函数体内一般不能有开关语句及循环语句
第3章 类与对象1
- 课后习题
①类定义结束以“ ; ”结束
②Time( int=0, int=0, int=0)有三个形参
③class类没有关键字public,private,protected时,访问属性为private
④类与对象的关系类似于数据类型与变量
任何一个对象只能属于一个具体的类
⑤一个类只能有一个析构函数
⑥拷贝构造函数的参数是某个对象的常引用名
- 平台习题
①私有成员变量不能赋初值
②p是一个指向类A公有数据成员m的公有指针成员,A1是类A的一个对象
可以用*A1.p=5给m赋值为5
③类的成员函数包括:构造函数,析构函数,拷贝构造函数
而友元函数不是类的成员函数
④一个类中可以有多个构造函数
构造函数在定义对象时自动执行
构造函数名必须和类名一致
构造函数无任何函数类型
⑤有参构造函数:A (int a);
无参构造函数:A ();
拷贝构造函数:A (const A& a);
赋值构造函数:A & operator = (const A& a);
⑥析构函数是在对象生存期结束时调用的
⑦成员函数不一定是内联函数
成员函数可以重载
成员函数可以是静态的
第4章 类与对象2
- 课后习题
①静态数据成员在类外初始化
静态数据成员是同类所有对象共有的
静态数据成员为public,才能用类名::成员名访问
②静态成员函数没有this指针
③常数据成员通过类构造函数的初始化列表进行初始化
例如:A(int a,int b):a(a),b(b)
常数据成员必须初始化,不能被更新,作用域为本类
例如:const int a=10;
④普通函数可以改变数据成员的值,常成员函数不可以改变数据成员的值
⑤常对象只能调用常函数,常函数可以被任何对象调用
void fun() const //常函数fun()
Time const t1(12,34,36); //常对象t1
class Point
{
public:
void a() //非静态成员函数
{ }
static void b() //静态成员函数
{ }
};
void main()
{
Point pt;
pt.a(); //通过对象调用非静态成员函数
pt.b(); //通过对象调用静态成员函数
Point::a(); //报错
Point::b(); //通过类名调用静态成员函数
}
- 平台习题
①常对象是各数据成员值不可改变的对象
常对象所属的类中也可以定义非常成员函数
②类中静态数据成员:static int count; 为其初始化:int Test::count=10;
③静态成员函数一般专门用来直接访问类的静态数据成员
第5章 继承与派生
- 课后习题
①派生类可以继承多个基类,派生类对基类默认的继承方式为private
在多层的类继承中,中间类既是上层类的派生类又是下层类的基类
如果基类构造函数没有形参或带有默认值,
派生类构造函数初始化列表中就不必对基类构造函数进行调用
②多重继承构造函数的调用顺序一般可分为4个步骤:
Step 1:任何虚基类,按照它们被继承的顺序依次调用构造函数。
Step 2:任何非虚基类,按照它们被继承的顺序依次调用构造函数。
Step 3:任何派生类,按照它们声明的顺序依次调用所属类的构造函数。
Step 4:调用派生类自己的构造函数。
③派生类构造函数的成员初始化列表,不能包含基类的成员对象所属类的构造函数
④在定义最后派生类对象时,将引起虚基类构造函数的调用,该函数只能被调用一次
- 平台习题
①基类对象/引用=公有派生类对象/引用,反之不成立
基类对象的指针=公有派生类对象的指针,反之不成立
例如:B是基类A的派生类,并有A aa, *pa=&aa; B bb, *pb=&bb;
bb=aa; (错误语句)aa=bb; (正确语句)
*pb = *pa; (错误语句)pa=pb; (错误语句,不是指针)
②派生类是基类的特殊化,具体化,定义的延续 ,
③派生类对象d可以用d.x的形式访问基类的成员x,则x是:公有派生的公有成员
④派生类默认继承方式为private继承
基类公有成员在派生类中属性可变
对基类成员的访问必须无二义性
赋值兼容规则也适用于多重公有继承
⑤多重继承中,如果基类有非私有属性的同名成员,
在派生类引用该同名成员时可以在该同名成员前增加:“基类名:: ”来区分
⑥派生类新增加的成员函数,其父类中私有继承的私有成员是不可直接访问的
⑦对象成员的构造函数由所在类的构造函数来调用
对象成员的访问类型可以使用任何类型
对象成员如果是公有类型也可以被继承
对象成员中的成员可以被所在类的成员函数访问
⑧在最后派生类构造函数的调用中,
先调用虚基类的构造函数,再调用其它基类的构造函数时,不再调用虚基类的构造函数。
第6章 多态性
- 课后习题
①C++语言中有5 个运算符不能重载:.、.*、::、?:、sizeof
②重载函数要求:参数个数不同或者参数类型不同
③运算符重载不可以改变运算符的个数,优先级,结合性,语法结构
④静态多态性可以使用函数重载和运算符重载获得
⑤抽象类是指含有纯虚函数的基类,其纯虚函数由派生类实现
纯虚函数是一种特殊的虚函数,它没有具体的实现代码
如果派生类不实现基类的纯虚函数,该派生类仍然为一个抽象类
- 平台习题
①抽象类的特性:不能说明其对象
②动态联编是用来在编译时确定操作函数的
③基类中说明了虚函数后,派生类中的函数可不必说明为虚函数
第7章 模板
- 课后习题
①函数模板:
因为99.0为double 类型,故 sizeof( x+y ) = sizeof( double ) = 8
template
T max(T x, T y)
{
return(x > y)?x : y;
}
变量int i; char c;
错误语句:max(i, c); 正确语句:max(i, i); max(c, c); max((int)c, i);
②模板的使用是为了提高代码的可重用性
③函数模板:
template < class T1, class T2 >
void sum(T1 x, T2 y)
{
cout << sizeof( x+y );
}
sum('1', 99.0) 的输出结果是:8
- 平台习题
①函数模板:
template
class Array
{
...
};
模板类定义:Arrayarr(100);
②函数模版:
template
void sum(T1 x, T2 y)
{
cout<<(x+y);
}
变量:int a; double b; char c;
错误语句:sum("abc", "ABC"); 正确语句:sum(a,a); sum(a,b); sum(b,c);
③函数模版:
template
T func(T x, T y)
{
return x * x + y * y;
}
正确的调用语句是: func(3,4)
④模板参数可以作为:数据成员的类型,成员函数的返回类型,成员函数的参数类型
⑤模板声明的开始部分:template
⑥模板的使用目的:提高代码的可重用性
第8章 文件及输入输出
- 课后习题
①执行文件输入/输出的操作,需要在程序中包含头文件名字空间 std 的 fstream 文件
②打开文件时,文件的所有使用方式:
ios::app // 输出到尾部
ios::ate // 寻找文件尾
ios::in // 文件输入
ios::out // 文件输出
ios::trunc // 删除同名文件
ios::binary // 二进制方式打开
ios::nocreate // 若文件不存在,则open()函数失败
ios::noreplace // 若文件存在,则open()函数失败
对于 ifstream 流,缺省值为 ios::in
对于 ofstream 流,缺省值为 ios::out
③在ios 类中控制格式的标志位中:
dec、oct、hex 分别是10进制、8进制、16进制的标志位
showbase 表示输出数值前面带有基数符号
④getline()、read() 和 get() 是读操作的函数,put() 是写操作的函数
⑤istream & istream :: seekg(long, seek_dir); 表示在输入流中移动文件读指针。
long 参数规定偏移量,正数表示向后移,负数表示向前移。
seek_dir 参数规定起始位置:beg:开始位置。cur:当前位置。end:结束位置。
例:已知 a 为 ifstream 流类的对象,并打开了一个文件
将对象 a 的读指针移到当前位置后100个字节处的语句是:a.seekg(100, ios::cur);
- 平台习题
①float data,以二进制方式将 data 的数据写入输出文件流类对象 x 中去的语句是:x.write((char *)&data, sizeof(float));
②打开文件 D:\file.txt,写入数据的语句是:fstream infile(" D:\file.txt ", ios::in | ios::out);
③read 函数的功能是从输入流中读取:指定若干个字符
Part 4/6 实验报告
实验报告一:类和对象的定义及使用
实验题目1
#include
#include
using namespace std;
class BookCard
{
private:
string id;
string stuName;
int number;
public:
BookCard(string i, string s, int n)
{
id=i;stuName=s;number=n;
}
BookCard()
{
id = "B19010250";stuName = "雪峰";number = 4;
}
void display()
{
cout << id <<' '<< stuName <<' '<< number << endl;
}
bool borrow()
{
if (number==10) {return false;}
else {number++;return true;}
}
};
void f(BookCard &bk)
{
if (!bk.borrow())
{
bk.display();
cout << "you have borrowed 10 books,can not borrow any more!" << endl;
}
else
bk.display();
}
int main()
{
BookCard bk1("B20190620", "东平", 10), bk2;
f(bk1);
f(bk2);
return 0;
}
实验题目2
#include
#include
using namespace std;
class Time
{
private:
int Hour;int Minute;int Second;
public:
Time(int H, int M, int S)//构造函数
{
Hour = H;Minute = M;Second = S;
}
~Time()//析构函数
{
}
void add( )//改变
{
Second++;
}
void set(int H, int M, int S)//设定
{
Hour = H;Minute = M;Second = S;
}
void PrintTime()//输出
{
cout << Hour << " : " << Minute << " : " << Second << endl;
}
};
void f(Time *t)
{
t-> PrintTime( );
}
int main()
{
Time t0(9, 18, 46);
t0.add();
f(&t0);
Time t1 = t0;//拷贝构造函数
t1.add();
f(&t1);
t0.set(1,2,34);
f(&t0);
return 0;
}
实验题目3
#include
#include
using namespace std;
class Girl;
class Boy
{
private:
string name;int age;
public:
Boy(string n, int a)//构造函数
{
name = n;age = a;
}
~Boy()//析构函数
{
}
friend void VisitBoyGirl(Boy &B, Girl &G);//友元
};
class Girl
{
private:
string name;int age;
public:
Girl(string n, int a)//构造函数
{
name = n;age = a;
}
~Girl()//析构函数
{
}
friend void VisitBoyGirl(Boy &B, Girl &G);//友元
};
void VisitBoyGirl(Boy &B, Girl &G)//顶层函数
{
cout << "Boy:" << B.name << " " << B.age << endl;
cout << "Girl:" << G.name << " " << G.age << endl;
}
int main()
{
Boy B("刘林峰",16);
Girl G("张三",18);
VisitBoyGirl(B,G);
return 0;
}
实验报告二:继承与派生实验
实验题目1
#include
#include
using namespace std;
class Vehicle
{
public:
int number;
Vehicle(int n):number(n)//构造
{cout<<"构造Vehicle"<
实验题目2
#include
using namespace std;
class Base//基类
{
public:
int b;
Base(int x): b(x){}//构造
void Show( ){cout<Show();
Derived *D1 = &D;//第三种赋值兼容
Base *B2 = D1;
B2->Show();
Base &B3=D;//第四种赋值兼容
B3.Show();
return 0;
}
实验报告三:继承与派生实验
实验题目1
#include
#include
using namespace std;
class Point
{
private:
double x,y;
public:
Point(double x=0.0,double y=0.0):x(x),y(y)//构造函数
{ }
Point & operator = (const Point &s)//赋值运算符
{
x=s.x;
y=s.y;
return *this ;
}
Point operator + (const double b)//双目运算符"+"
{
Point tempt;
tempt.x=this->x+b;
tempt.y=this->y+b;
return tempt;
}
Point operator + (const Point &b)//双目运算符"+"
{
Point tempt;
tempt.x=this->x+b.x;
tempt.y=this->y+b.y;
return tempt;
}
Point operator ++ ( )//前置"++"运算符
{
++x; ++y;
return *this;
}
friend Point operator - (const Point &a, const Point &b)//双目运算符"-"
{
Point tempt;
tempt.x=a.x-b.x;
tempt.y=a.y-b.y;
return tempt;
}
friend ostream & operator << ( ostream &out , const Point &s)//插入运算符
{
out <<"("<< s.x<<","<
实验题目2
#include
#include
using namespace std;
const double PI = 3.1415 ;
class Container//容器
{
public:
virtual double area ( ) const = 0 ;
virtual double volume ( ) const = 0 ;
};
class Cube :public Container//正方体
{
private:
double a;
public:
Cube(double a):a(a)
{ }
double area() const
{
return a * a * 6;
}
double volume() const
{
return a * a * a;
}
void show()
{
cout << "正方体边长为:" << a << " 表面积为:" << this->area() << " 体积为:" << this->volume() << endl;
}
};
class Sphere :public Container//球体
{
private:
double r;
public:
Sphere(double r):r(r)
{ }
double area() const
{
return 4 * PI * r * r;
}
double volume() const
{
return 4.0 / 3 * PI * r * r * r;
}
void show()
{
cout << "球体半径为:" << r << " 表面积为:" << this->area() << " 体积为:" << this->volume() << endl;
}
};
class Cylinder :public Container//圆柱体
{
private:
double r,h;
public:
Cylinder(double r, double h):r(r),h(h)
{ }
double area() const
{
return 2 * PI * r * h + 2 * PI * r * r;
}
double volume() const
{
return PI * r * r * h;
}
void show()
{
cout << "圆柱的底面半径为:" << r << " 高为:" << h << " 表面积为:" << this->area() << " 体积为:" << this->volume() << endl;
}
};
int main()
{
Cube cu(3);
Sphere sp(2);
Cylinder cy(2,3);
cu.show();
sp.show();
cy.show();
return 0;
}
实验报告四:流运算符的重载及文件的使用
实验题目1
#include
#include
using namespace std;
class Course
{
private:
string name;
int num;
public:
friend istream & operator >> (istream &in , Course &a )//提取运算符“>>”
{
in>>a.name>>a.num;
return in;
}
friend ostream & operator << (ostream &out , Course &a )//插入运算符“<<”
{
out<>b;
cout<
实验题目2
#include
#include
using namespace std;
void ReadFile(char *s)
{
ifstream a ( s ) ;
if( !a )
{
cout << s <<" cannot be openned!" << endl ;
}
char ch;
while( a.get( ch ) )
{
cout<='a'&&ch<='z')
{
y.put( ch-32 ) ; //ascii码中大小写相差32
}
else
{
y.put( ch ) ;
}
}
x. close( );
y. close( );
}
int main ( )
{
ReadFile("ff.txt"); //txt需放在当前目录
Change ("ff.txt" ,"ff2.txt");
ReadFile("ff2.txt");
return 0;
}
实验题目3
#include
#include
using namespace std;
class Student
{
private:
char *nu;char *na;char *se;int s;//学号、姓名、性别、成绩
public:
Student(char *nu="00",char *na="null",char *se="null",int s=0):nu(nu),na(na),se(se),s(s)//构造函数
{ }
friend ostream & operator<<(ostream &out,const Student &s)//重载输出运算符<<
{
out<
Part 5/6 平台练习
第二章
0x01 动态空间管理
#include
using namespace std;
int main()
{
int num,i,positive,negative;
positive=negative=0;
cin>>num;
int *p=new int[20];
for(i=0;i>p[i];
}
for(i=0;i0)positive++;
if(p[i]<0)negative++;
}
if(num>20||num<1)cout<<"number error.\n";
else
{
cout<<"There are "<
0x02 求圆的面积与周长
#include
using namespace std;
int main()
{
double r,s,c;
cin>>r;
s=3.14159*r*r;
c=3.14159*2*r;
cout<<"s="<
第三章
0x01 简单图书管理
#include
#include
using namespace std;
class Book
{
private:
string bookname;float price;int number;
public:
Book(string name,float p,int n);
void borrow()
{
number--;
}
void restore()
{
number++;
}
void display();
} ;
void Book::display()
{
cout<
0x02 友元函数的定义与使用
#include
#include
using namespace std;
class Stu
{
public:
Stu(string name,int score);
friend void print();
string name;
int score;
} ;
class Tea
{
public:
Tea(string name,string pro);
friend void print();
string name;
string pro;
} ;
Stu::Stu(string n,int s){
name=n;
score=s;
}
Tea::Tea(string n,string p){
name=n;
pro=p;
}
void print(Stu S,Tea T)
{
cout<<"student's name:"<>stuname;
cout<<"请输入教师姓名:"<>teaname;
cout<<"请输入教师职称:"<>teapro;
Stu student(stuname,88);
Tea teacher(teaname,teapro);
print(student,teacher);
return 0;
}
0x03 立方体类的定义与使用
#include
#include
using namespace std;
class Cube
{
public:
int l,w,h;
Cube(int L=3,int W=2,int H=1);
int Compute()
{
return(l*w*h);
}
};
Cube::Cube(int L,int W,int H)
{
l=L;w=W;h=H;
}
int main()
{
int l,w,h;
cout<<"输入立方体的长宽高:"<>l>>w>>h;
Cube A(l,w,h);
Cube B;
cout<
0x04 设计汽车类
#include
#include
using namespace std;
class Car
{
private:
string brand;string type;int year;double price;
public:
Car(string b,string t,int y,double p);
Car()
{
brand="undefinition";
type="undefinition";
year=2000;
price=0;
}
string GetBrand()
{
return brand;
}
string GetType()
{
return type;
}
int GetYear()
{
return year;
}
double GetPrice()
{
return price;
}
};
Car::Car(string b,string t,int y,double p){
brand=b;
type=t;
year=y;
price=p;
}
int main()
{
Car car1("FIAT","Palio",2007,6.5);
cout<
0x05 设计学生类
#include
#include
using namespace std;
class Student
{
private:
int age;string name;
public:
Student(int a, string m);
Student()
{
age=0;name="unnamed";
}
void SetMember(int a, string m)
{
age=a;name=m;
}
int Getage()
{
return age;
}
string Getname()
{
return name;
}
};
Student::Student(int a,string m)
{
age=a;name=m;
}
int main( )
{
Student stu[3]={Student(13,"wang")} ; /*第一个元素用带参构造函数初始化;第二、三个元素由无参构造函数初始化,默认年龄为 0 ,姓名为 "unnamed"*/
stu[2].SetMember(12,"zhang"); /*修改第三个元素的数据成员值*/
cout<
第四章
静态数据成员的使用
#include
#include
using namespace std;
class Student
{
private:
int age;string name;
public:
static int count;
Student(int m,string n)
{
age=m;name=n;count++;
}
Student()
{
age=0;name="unnamed";count++;
}
~Student()
{
count--;
}
void Print()const
{
cout<<"count="<Print();
delete p;
s1.Print();
Student Stu[4];
cout<<"count="<
第五章
0x01 简易工资管理
#include
#include
using namespace std;
class Employee
{
public:
string name;int working_years;
Employee(string n,int y):name(n),working_years(y){}//构造函数
string Getname(){return name;}//名字
void SetWorkyears(int wy){working_years=wy;}//工作年龄
};
class Worker:public Employee
{
public:
double pay_per_hour;int work_time;
Worker(string n,int y,int x):Employee(n,y),work_time(x){}//构造函数
double count_pay(){return work_time*pay_per_hour+35*working_years;}//计算
void SetWorktime(int wt){work_time=wt;}//工作时长
void Setpay_per_hour(int x){pay_per_hour=x;}//时薪
};
class SalesPerson:public Employee
{
public:
double pay_per_hour;double saleroom;int work_time;
SalesPerson(string n,int y,double sr,int x):Employee(n,y),saleroom(sr),work_time(x){}//构造函数
double count_pay(){return work_time*pay_per_hour+35*working_years+1.0*saleroom/100;}//计算
void SetWorktime(int wt){work_time=wt;}//工作时长
void Setpay_per_hour(int x){pay_per_hour=x;}//时薪
void Setsalesroom(double sr){saleroom=sr;}//售出金额
};
class Manager:public Employee
{
public:
Manager(string n,int y):Employee(n,y){}//构造函数
double count_pay(){return 1000+35*working_years;}//计算
};
int main()
{
Worker work("zhangqiang",3,200);
work.Setpay_per_hour(50);
cout<<"工资="<
0x02 长方体计算
#include
#include
using namespace std;
class S
{
protected:
float length; float width;
public:
S(float l, float w):length(l),width(w) {}//构造函数
float area(){return length*width; }
void disp(){cout<>l>>w>>h;
V a(l,w,h);
a.disp();
return 0;
}
第六章
0x01 动态多态性
#include
using namespace std;
const double PI = 3.1415 ;
class shape
{
public:
virtual double volume ( ) = 0 ;//纯虚函数
};
class cylinder:public shape
{
private:
double h , r;
public:
cylinder (double r , double h ):h(h) , r(r)//重载
{ }
double volume()
{
return h*PI*r*r ; //圆柱的体积
}
};
class sphere:public shape
{
private:
double r ;
public:
sphere(double r) : r( r )//重载
{ }
double volume()
{
return 4*PI*r*r*r/3; //球的体积
}
};
int main()
{
shape *p;
double r,h;
cout<<"input r & h:"<>r>>h;
cylinder cy(r,h);
sphere sp(r);
p=&cy;
cout< volume()< volume()<
0x02 矩阵类运算符重载
#include
#include
using namespace std;
class Matrix
{
private:
int row,col,*m;
public:
Matrix(int r,int c):row(r),col(c)//重载
{
cout<<"请输入该矩阵元素:"<> m[i];
}
}
Matrix():row(3),col(3)//重载
{
m = new int[9];
}
friend Matrix operator + (const Matrix &a, const Matrix &b)//加
{
Matrix tempt;
if(a.row!=b.row||a.col!=b.col)
{
cout<<"program terminated!"<>row_a>>col_a;
Matrix am(row_a,col_a);
cout<<"请输入bm矩阵的行数和列数:"<>row_b>>col_b;
Matrix bm(row_b,col_b),cm;
cout<<"am:"<
Part 6/6 编程练习
第2章 对C的改进及扩展
基本格式
#include
using namespace std;
int main( )
{
return 0;
}
bool类型
bool Larger(int x , int y)
{
if ( x > y )
return true;
return false;
}
int main( )
{
int x , y;
cin >> x >> y;
bool t = Larger(x , y);
// false为 0,true为 1
cout << boolalpha << t << endl << noboolalpha << t << endl;
return 0;
}
名字空间
namespace one
{
int M = 200;
int f = -10;
}
namespace two
{
int f = -100 ;
}
using namespace one ;
int main( )
{
cout << M << endl;
cout << f << endl;
using two::f;
f = 123;
cout << f << endl;
return 0;
}
string类型应用,insert,replace,substr,find,erase函数
int main( )
{
string s1, s2, s3;
cin >> s1; // 读入不带空格的字符串,例如 "ABC"
cout << s1 << endl;
getline(cin,s1); // 读入带空格的字符串,例如 " A BC"
cout << s1 << endl;
s2 = "Student";
s3 = s2;
cout << s3 << endl;
string s4 (8, 'A'); // "AAAAAAAA"
cout << s4 << endl;
s2 = s3 + '&' + s4 ; // "Student&AAAAAAAA"
cout << s2 << endl;
s3.insert(7 , "&Teacher"); // "Student&Teacher"
cout << s3 << endl;
s3.replace(2 , 4 , "ar"); // "uden" 替换为 "ar","Start&Teacher"
cout << s3 << endl;
s1 = s3.substr(6 , 7); // 从 "Start&Teacher"中获取 "Teacher"
cout << s1 << endl;
int pos = s3.find(s1); // s1在s3中第 6 位
cout << pos << endl;
s3.erase(5 , 8); // 从 "Start&Teacher"中删除 "&Teacher"
cout << s3 << endl;
bool f = s1 > s4; // true
cout << boolalpha << f << endl;
return 0;
}
全局变量与局部变量
int A = 20;
int main( )
{
int a[3] = {10 , 20 , 30};
int A = 0;
// 局部变量 A=60
for (int i = 0 ; i < 3 ; i++){
A+=a[i];
}
::A += A; // 全局变量 ::A=80
cout << A << endl << ::A << endl;
return 0;
}
形参带默认参数值的函数
void Fun( int i , int j , int k=10 ){
cout << i << " "<< j << " " << k << endl;
}
int main( )
{
// Fun ( 20 ); 报错
Fun ( 20 , 30 ); // k默认为 10
Fun ( 20 , 30 , 40 ); // k替换为 40
return 0;
}
重载函数
int square ( int x ){
cout << x * x << endl;
}
float square ( float x ){
cout << x * x << endl;
}
double square ( double x ){
cout << x * x << endl;
}
int main( )
{
square ( 11 );
square ( 1.1f );
square ( 1.11 );
return 0;
}
引用的声明及访问
int x = 5 , y = 10 ;
int &r = x ;
void print( ){
cout << "x= " << x << " y= " << y << " r= " << r << endl ;
cout << "Address of x " << &x << endl;
cout << "Address of y " << &y << endl;
cout << "Address of r " << &r << endl;
}
int main( )
{
print (); // x=5 y=10 r=5
y = 100;
x = y - 10;
print (); // x=90 y=100 r=90
return 0;
}
引用作参,修改实际参数的值
void swap ( int &x , int &y ){
int t = x ; //t=3
x = y ; //x=5
y = t ; //y=3
}
int main( )
{
int a = 3 , b = 5 ;
swap ( a , b ) ;
cout << "a= " << a << " b= " << b << endl;
return 0;
}
三种参数的使用
int Fun (const int &x , int &y , int z){
// x++ ; 报错,x不可修改
y++ ;
z++ ;
return y ;
}
int main( )
{
int a = 1, b = 2, c = 3, d = 0;
d = Fun ( a , b , c ) ; // a不变,b=2+1,c不变,d=b
cout << "a=" << a << " b=" << b << " c=" << c << " d=" << d << endl;
return 0;
}
异常处理过程和方法
double divide(int x,int y){
// 如果分母为零,抛出异常
if ( y == 0 ){
throw 2.333;
}
return x*1.0 / y;
}
int main( )
{
int a = 9, b = 5, c = 0;
// 检查是否出现异常
try{
cout << "a/b = " << divide (a , b) << endl;
cout << "b/a = " << divide (b , a) << endl;
cout << "a/c = " << divide (a , c) << endl;// 失败,不再try
cout << "c/b = " << divide (c , b) << endl;// 没有执行
}
// catch到小数2.333
catch ( double ){
cout << "有分母为零的情况" << endl;
}
return 0;
}
第3章 类与对象1
类对象数据成员
class CDate{
public:
int year;
int month;
int day;
};
int main( )
{
CDate date1;
CDate date2;
int age(0);// int age=0
date1.year = 2019; date1.month = 3; date1.day = 9;
date2.year = 1999; date2.month = 3; date2.day = 9;
age = date1.year - date2.year;
cout << "He is " << age << " years old" << endl;
cout << date2.year << " - "<< date2.month << " - " << date2.day << endl;
cout << "date1 occupies " << sizeof(date1) << " bytes."; // 3 * 4 =12
return 0;
}
this 指针
class CDate{
private:
int Year, Month, Day;
public:
void SetDate(int y,int m,int d){
Year = y;
Month = m;
Day = d;
}
void Display( ){
cout << "this 指针是: "<< this < Year << endl;
cout << "Month地址: "<< &this -> Month << endl;
cout << "Day地址: "<< &this -> Day << endl;
}
};
int main( )
{
CDate a ;
a.SetDate (2019, 3, 9);
cout << "a地址: " << &a << endl;
a.Display();
return 0;
}
两种方式创建对象
class CDate{
int Year, Month, Day;
public:
CDate(int y=2000, int m=1, int d=22 ){
Year = y; Month = m; Day = d;
}
void Display( ){
cout << this->Year << " - "<< this->Month << " - " << this->Day << endl;
}
};
int main( )
{
CDate day1 (2019,3);// 初始化 day1
CDate day2 = day1; // 用day1初始化 day2
day1.Display();
day2.Display();
return 0;
}
构造与析构顺序
class CDate
{
int year, month, day ;
public:
// 构造函数
CDate(int y=2000, int m=1, int d=1):year(y), month (m), day(d){
cout << "构造成功" << endl;
}
// 拷贝构造函数
CDate(const CDate &x){
year = x.year; month = x.month; day = x.day + 1;
cout << "拷贝构造成功" << endl;
}
void Display ( ){
cout<< year << "-" << month << "-" << day << endl;
}
// 析构函数
~CDate(){
cout << "析构成功" << endl;
}
};
CDate f (CDate day1){
CDate day2 (day1);
return day2;
}
int main( )
{
CDate day1 (2019,3,9) ; // 构造 day1
CDate day3; // 构造 day3
CDate day2 (day1) ; // 拷贝构造 day2, 9+1=10
CDate day4 = day2; // 拷贝构造 day4, 10+1=11
day3 = day2; // 拷贝构造 day3
day3 = f (day2); // 拷贝构造 day3, 11+1=12
// f 里的 day2,day1依次析构
day3.Display( ); //2019-3-12
// day4,day3,day2,day1依次析构
return 0;
}
类对象数组,初始化及访问
class CDate{
int year, month, day;
public :
CDate(int y=2000, int m=1, int d=1): year(y), month (m), day(d)
{ }
void Display ( ){
cout<< year << "-" << month << "-" << day << endl;
}
};
int main( )
{
CDate x[3]={ CDate(2019,3,8), CDate(2019,3,11) };
for(int i=0; i< 3; i++){
x[i].Display( );
}
return 0;
}
第4章 类与对象2
包含类1
class A{
public:
A( ){
cout << "创建A" << endl;
}
~A( ){
cout << "析构A" << endl;
}
};
class B{
public:
B( ){
cout << "创建B" << endl;
}
~B( ){
cout << "析构B" << endl;
}
private:
A a;// B类包含了A类
};
int main( )
{
B b;
return 0;
}
包含类2
class CDate{
int year, month, day;
public :
CDate(int y, int m, int d):year(y),month (m),day(d) {
cout << "CDate 构造成功" << endl;
}
void Display( ){
cout<< year << "-" << month << "-" << day << endl;
}
~CDate(){
cout << "CDate 析构成功" << endl;
}
};
class Croster{
private:
string name;
CDate birthday;// Croster类包含了CDate类
public:
Croster(string na, int y, int m, int d): birthday( y, m, d){
cout << "Croster 构造成功" << endl;
name = na;
}
void Display(){
cout << name << " : ";
birthday.Display();
}
~Croster(){
cout << "Croster 析构成功" << endl;
}
};
int main()
{
Croster stuA("赵焱", 2001, 1 ,29 );
stuA.Display();
return 0;
}
静态数据成员1
class Croster{
public:
static int Count;
private:
string name; int Math; int English;
public:
Croster(string na="undefine", int m= 100, int e= 100): name(na), Math(m), English(e){
cout << "欢迎新同学!" << endl ;
Count -- ;
}
};
int Croster :: Count = 100;// 初始化静态数据成员
int main()
{
cout << "人数 : " << Croster::Count << endl;
Croster list[3];
cout << "人数 : " << list[1].Count << endl;
Croster A;
cout << "人数 : " << A.Count << endl;
return 0;
}
静态数据成员2
class Croster{
public:
static int Count;
private:
string name; int Math; static int Sum;
public:
Croster(string na= "undefine", int m= 100): name(na), Math(m){
cout << "欢迎新同学!" << endl ;
Count -- ;
Sum += Math;
}
static void Display(){
// cout << "name: " << name << endl; 报错
cout << "Sum = " << Sum << ", ";
if ( Count == 100 ){
cout << "Average = 0 " << endl;
}
else{
cout << "Average = " << Sum* 1.0/ (100-Count) << endl;
}
}
};
int Croster :: Count = 100;
int Croster :: Sum;// 默认初始值为0
int main()
{
Croster::Display();
Croster list[3] ={ Croster("赵焱",95), Croster("钱朵", 90), Croster("孙力", 92) };
list[2].Display();
return 0;
}
静态数据成员3
class Croster{
private:
string name;
double GPA, Math;
static const double Score ;
public:
Croster(string na= "undefine", double m= 100){
name = na; Math = m ;
}
double GetGPA(){
GPA = Math/10 - Score;
return GPA;
}
void Display(){
cout << name << "的成绩为:" << Math << ", " << "绩点为:" << GetGPA() << endl;
}
};
const double Croster::Score = 5.00;
int main()
{
Croster A("赵焱", 93.5);
A.Display();
return 0;
}
第5章 继承与派生
单继承
#include
using namespace std;
class Base
{
private:
int b1;
protected:
int b2;
public:
void set(int m, int n){
b1 = m;
b2 = n;
}
void show( ){
cout << "b1 = " << b1 << endl;
cout << "b2 = " << b2 << endl;
}
};
class Derived: public Base// 公有派生类
{
private:
int d;
public:
void set2(int m, int n, int l){
set(m,n);
d = l;
}
void show2( ){
show( );
cout << "d = " << d << endl;
}
};
int main( )
{
Derived obj;
obj.set2(30, 40, 50);
obj.show( );
obj.show2( );
return 0;
}
多重继承
#include
using namespace std;
class BaseA
{
private: int a1;
protected: int a2;
public: int a3;
void setA(int x, int y, int z){
a1 = x; a2 = y; a3 = z;
}
void showA( ){
cout << " a1 = " << a1 << ", a2 = " << a2 << ", a3 = " << a3 << endl;
}
};
class BaseB
{
private: int b1;
protected: int b2;
public: int b3;
void setB(int x, int y, int z){
b1 = x; b2 = y; b3 = z;
}
void showB( ){
cout << " b1 = " << b1 << ", b2 = " << b2 << ", b3 = " << b3 << endl;
}
};
class BaseC
{
private: int c1;
protected: int c2;
public: int c3;
void setC(int x, int y, int z){
c1 = x; c2 = y; c3 = z;
}
void showC( ){
cout << " c1 = " << c1 << ", c2 = " << c2 << ", c3 = " << c3 << endl;
}
};
class Derived: public BaseA, protected BaseB, private BaseC
{
private: int d1;
protected: int d2;
public: int d3;
void setD(int x, int y, int z){
d1 = x; d2 = y; d3 = z;
}
void showD( ){
cout << " d1 = " << d1 << ", d2 = " << d2 << ", d3 = " << d3 << endl;
}
void setall(int x0, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8, int x9, int x10, int x11 ){
setA(x0, x1, x2);
setB(x3, x4, x5);
setC(x6, x7, x8);
setD(x9, x10, x11);
}
void showall( ){
showA( ); showB( ); showC( ); showD( );
}
};
int main( )
{
Derived obj;
obj.setall(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120);
obj.showA( );// showA( )为 public成员,可以通过 obj访问
// obj.showB( ); showB( )为 protected成员,无法通过 obj访问
// obj.showC( ); showC( )为 private成员,无法通过 obj访问
obj.showD( );
obj.showall( );
return 0;
}
构造,析构
#include
using namespace std;
class Base//基类
{
public:
Base( ){cout << "构造A"<
多重继承下构造,析构
#include
using namespace std;
class Grand
{
public:
int a;
Grand(int n): a(n)// a=1
{cout << "构造Grand, a = " << a << endl;}
~Grand( ){cout << "析构Grand" << endl;}// 析构
};
class Father: public Grand
{
public:
int b;
Father(int n1,int n2): Grand(n1), b(n2)// Grand(1), b=2
{cout << "构造Father, b = " << b << endl;};
~Father( ){cout << "析构Father" << endl;}// 析构
};
class Mother
{
public:
int c;
Mother(int n): c(n)// c=2
{cout << "构造Mother, c = " << c << endl;}
~Mother( ){cout << "析构Mother" << endl;}// 析构
};
class Son: public Father, public Mother
{
public:
int d;
Son(int n1, int n2, int n3, int n4): Father(n1, n2), Mother(n3), d(n4)// Father(1,2), Mother(3), d=4
{cout << "构造Son, d = " << d << endl;}
~Son( ){cout << "析构Son" << endl;}// 析构
};
int main( )
{
Son s(1,2,3,4);
return 0;
}
派生类,基类有同名成员
#include
using namespace std;
class Base
{
public:
int a;
Base(int x){
a = x;
}
void Print1( ){
cout << "Base::a = " << a << endl;
}
};
class Derived: public Base// 派生类
{
public:
int a;
Derived(int x, int y): Base(x){
a = y;
Base::a *= 2 ;
}
void Print2( ){
Base::Print1( );
cout << "Derived::a = " << a << endl;
}
};
void f1(Base &obj) {obj.Print1( );}
void f2(Derived &obj) {obj.Print2( );}
int main( )
{
Derived d(200,300) ;
d.Print2( ); // 输出1, 2行
d.a = 400;
d.Base::a = 500;
d.Base::Print1( ) ; // 输出3行
Base *pb;
pb = &d;
pb -> Print1( ); // 输出4行
f1(d); // 输出5行
Derived *pd;
pd = &d;
pd -> Print2( ); // 输出6,7行
f2(d); // 输出8,9行
return 0;
}
多重继承中,直接基类有同名成员
class Base1{
public:
int a;
Base1(int x):a(x){
cout << "Base1 a = " << a << endl;
}
};
class Base2{
public:
int a;
Base2(int x):a(x){
cout << "Base2 a = " << a << endl;
}
};
class Derived: public Base1, public Base2{
public:
Derived(int x,int y):Base1(x),Base2(y){
Base1::a *= 2 ;
Base2::a *= 2 ;
cout << "Derived from Base1::a = "<
虚基类
class Base{
public:
int a;
Base(int x): a(x){
cout << "Base a = " << a << endl;
}
};
// 虚基类一
class Base1: public virtual Base{
public:
int b;
Base1(int x, int y): Base(y), b(x){
cout << "虚基类一 a = " << a << endl;
cout << "虚基类一 b = " << b << endl;
}
};
// 虚基类二
class Base2: public virtual Base{
public:
int c;
Base2(int x, int y): Base(y), c(x){
cout << "虚基类二 a = " << a << endl;
cout << "虚基类二 c = " << c << endl;
}
};
class Derived: public Base1, public Base2{
public:
// Base1(10, 20), Base2(20, 40), Base(30)
Derived(int x, int y): Base1(x, y), Base2(2*x, 2*y), Base(3*x){
cout << "a = " << a << endl << "b = " << b << endl << "c = " << c << endl;
cout << "Base::a = " << Base::a << endl << "Base1::a = " << Base1::a << endl << "Base2::a = " << Base2::a << endl;
}
};
int main( ){
Derived obj(10, 20);
return 0;
}
赋值兼容规则
class Base{
public:
int b;
Base(int x): b(x){ }
int getb( ){ return b; }
};
class Derived: public Base{
public:
int d;
Derived(int x, int y): Base(x), d(y){ }
int getd( ){ return d; }
};
int main( ){
Base B(11);
Derived D(22, 33);
// 第一种赋值兼容
B = D;
// 第二种赋值兼容
Base *B1 = &D;
// 第三种赋值兼容
Derived *D1 = &D;
Base *B2 = D1;
// 第四种赋值兼容
Base &B3 = D;
cout << "B.getb( ) = " << B.getb( ) << endl;
cout << "B1->getb( ) = " << B1->getb( ) << endl;
cout << "B2->getb( ) = " << B2->getb( ) << endl;
cout << "B3.getb( ) = " << B3.getb( ) << endl;
return 0;
}
第6章 多态性
静态多态性
class Student{
string name;
int no;
public:
Student():name("同学"),no(0){
}
Student(string s, int n): name(s), no(n){
}
void print(){
cout << name << " " << no << endl;
}
void print(int x){
cout << name << " B" << x << " "<< no << endl;
}
};
int main( ){
Student s1;
s1.print ( );
Student s2("学生", 18);
s2.print ( );
s2.print (2019);
return 0;
}
重载运算符 "+"
class Complex{
private:
float real, imag;
public:
Complex (float r = 0, float i = 0):real(r),imag(i){
}
void print ( ){
cout << real << "+" << imag << "i" <
重载运算符 "="
#include
#include
using namespace std;
class CMessage{
private:
char* p;
public:
CMessage(char* text = "ABC"){
// 申请动态空间
p = new char[strlen(text) + 1];
strcpy(p, text);
}
void show(){
cout << p <
重载运算符 “[ ]"
class Array{
int *m, num;
public:
Array(int n):num(n){
m = new int [num];
for (int i = 0; i < num; i++){
m[i] = (i+1)*10;
}
}
// 调用运算符
int & operator [] (int r){
if(r>=0 && r
重载运算符 ">>","<<"
class Complex{
float real, imag;
public:
Complex (float r=0, float i=0): real(r),imag(i){
}
friend istream & operator >> (istream &i, Complex &a){
i >> a.real >> a.imag ;
return i;
}
friend ostream & operator << (ostream &o, Complex &a){
o << a.real << "+" << a.imag << "i" << endl;
return o;
}
};
int main( ){
Complex c1, c2;
cout << "input c1, c2:" << endl;
cin >> c1 >> c2;
cout << "c1 = " << c1 << "c2 = " << c2;
return 0;
}
重载运算符 “++”,“--”
class Complex{
float real, imag;
public:
Complex operator -- ( ){
--real; --imag;
return *this;
}
Complex operator ++ ( ){
++real; ++imag;
return *this;
}
Complex operator -- (int){
Complex t(*this);
real--; imag--;
return t;
}
Complex operator ++ (int){
Complex t(*this);
real++; imag++;
return t;
}
friend istream & operator >> (istream &i, Complex &a){
i >> a.real >> a.imag ;
return i;
}
friend ostream & operator << (ostream &o, Complex &a){
o << a.real << "+" << a.imag << "i";
return o;
}
};
int main( ){
Complex c1, c2;
cout << "input c1, c2:" << endl;
cin >> c1 >> c2;
cout << "c1 = " << c1 << "c2 = " << c2;
c1++; cout << "c1++ = " << c1 << endl;
++c1; cout << "++c1 = " << c1 << endl;
c2++; cout << "c2++ = " << c2 << endl;
++c2; cout << "++c2 = " << c2 << endl;
return 0;
}
虚函数的 Print()
class Base{
public:
int a;
Base(int x):a(x){
}
virtual void Print( ){
cout << "Base::a = " << a << endl;
}
};
class Derived: public Base{
public:
int a;
Derived(int x, int y): Base(x),a(y){
Base::a *= 2 ;
}
void Print( ){
Base::Print( );
cout << "Derived::a = " << a << endl;
}
};
void f1(Base &x){
x.Print( );
}
void f2(Derived &x){
x.Print( );
}
int main( ){
Derived d(200,300) ; // Base(200), d.a(300)
d.Print( );
d.a = 400; // d.a(400)
d.Base::a = 500; // Base(500)
d.Base::Print( ) ;
Base b(8); // b.a(8)
Base *pb;
pb = &b; // pb->a=8
pb -> Print( );
pb = &d; // pb-> Base::a=500, pb-> a=400
pb -> Print( );
f1(b);
f1(d);
Derived *pd;
pd = &d; // pd-> Base::a=500, pd-> a=400
pd -> Print( );
f2(d);
return 0;
}
虚函数的析构
class A{
public:
virtual ~A( ){
cout << "析构A"<< endl;
}
};
class B: public A{
public:
virtual ~B ( ){
cout << "析构B" << endl;
}
};
int main( ){
A *a = new B();
delete a ;
return 0;
}
虚函数的同名覆盖
class base{
public:
// 虚函数
virtual void f1( ){
cout << "f1() of base "<< endl ;
}
// 虚函数
virtual void f2( ){
cout << "f2() of base "<< endl ;
}
};
class derive: public base{
public:
void f1( ){
cout << "f1() of derive "<< endl;
}
void f2 (int x){
cout << "f2() of derive "<< endl;
}
// 普通函数
void f3(){
cout << "f3() of derive "<< endl;
}
};
int main(){
derive x;
x.f1 ( );
x.base::f2( );
x.f2 (1);
x.f3 ( );
return 0;
}
纯虚函数
class Point{
public:
// 纯虚函数
virtual void Draw () = 0 ;
};
class Line:public Point{
public:
void Draw ( ){
cout << "Line::Draw is called"< Draw( );
}
int main(){
// Point p; 报错
Line L; Function(&L);
Circle C; Function(&C);
return 0;
}
纯虚函数的抽象类
class Shape{
public:
virtual double area( )= 0 ;
};
class Triangle: public Shape{
double base, hight;
public:
Triangle (double b, double h):base(b), hight(h){
}
double area(){
return 1/2*base*hight;
}
};
class Rectangle:public Shape{
double hight, width;
public:
Rectangle(double h, double w):hight(h), width(w){
}
double area(){
return hight*width ;
}
};
class Circle:public Shape{
double radius;
public:
Circle(double r):radius(r){
}
double area(){
return 3.14*radius*radius;
}
};
int main(){
Shape *p[3];
p[0] = new Rectangle (2.5, 10.0);
p[1] = new Rectangle(15, 22);
p[2] = new Circle(3.0);
cout << "三角形面积: " << p[0]->area( ) << endl ;
cout << "长方形面积: " << p[1]->area( ) << endl ;
cout << "圆形面积: " << p[2]->area( ) << endl;
return 0;
}
第7章 模板
函数模板
// 函数模板
template
T Max(T x, T y){
return x>y ? x:y;
}
int main(){
cout << Max(2, 8) << endl;
cout << Max(2.5, 8.5) << endl;
// cout << Max(2, 8.5) << endl; 报错
cout << Max (2, 8.5) << endl;
cout << Max (2, 8.5) << endl;
return 0;
}
模板函数的重载
#include
#include
using namespace std;
template
T Max(T x, T y){
return x>y ? x:y;
}
char* Max(char* x, char* y){
return (strcmp(x,y)>0 ? x:y);
}
int main(){
cout << Max('2', '8') << endl;
cout << Max("gorilla", "star") << endl;
return 0;
}
类模板
template
void sum(A a1, B a2){
cout << (a1+a2);
}
int main(){
string a = "abc";
string b = "cba";
sum(a,b);
return 0;
}
第8章 文件及输入输出
cin,cin.get( ),cin.getline( ),getline( )
int main() {
char s1[80], s2[80], s3[80];
string str1, str2;
cout << "Enter sentence A: " << endl;
cin >> s1;
cin.get (s2, 80);
cout << "Enter sentence B: " << endl;
cin >> s1;
cin.getline(s3, 80);
cout << "Enter sentence C: " << endl;
cin >> str1;
getline (cin, str2);
cout << "cin: " << s1 << endl;
cout << "cin.get: " << s2 << endl;
cout << "cin: " << s1 << endl;
cout << "cin.getline: " << s3 << endl;
cout << "cin: " << str1 << endl;
cout << "getline: " << str2 << endl;
return 0;
}
setf( ),unsetf( )
int main( ){
cout.setf ( ios::showpos );
cout.setf ( ios::scientific ); //科学计数法
cout << 123 << " " << 123234.5 << endl;
cout.unsetf ( ios::showpos );
cout << 123 << " " << 123234.5 << endl;
return 0;
}
操纵函数 setw
#include
#include
using namespace std;
int main(){
int i = 6789, j = 1234, k = -10;
cout << setw(6) << i << j << k << endl;
cout << setw(6) << i << setw(8) << j << setw(10) << k << endl;
return 0;
}
输出控制符函数 setup
#include
#include
using namespace std;
ostream & setup (ostream &s){
s.setf ( ios::left ); //左对齐
s << setw(10) << setfill('$'); //域宽10,空白处用$填充
return s;
}
int main(){
cout << 10 << "Hello!" << endl;
// 10 域宽2,"Hello!" 域宽6
cout << setup << 10 << "Hello!" << endl;
cout << setup << 10 << setup << "Hello!" << endl;
return 0;
}
“>>”,“<<” 文本操作
#include
#include
#include
using namespace std;
void CreateFile(){
ofstream x ( "d:\\f1.txt" );
x << 10 << " " << 3.1415926;
x << "~ This is a short text file ~";
x.close();
}
void ReadFile(){
int i; double d; string str;
ifstream y ( "d:\\f1.txt" );
y >> i >> d ;
cout << i << " " << d <
get(),put() 文本操作
int main ( ){
//打开文本
ifstream x ( "d:\\abc.txt" );
ofstream y ( "d:\\xyz.txt" );
char c;
//复制和输出
while(x.get(c)){
y.put(c);
cout.put(c);
}
x. close( );
y. close( );
return 0;
}
read(),write() 文本操作
void CreateBiFile( ){
ofstream x ( "d:\\test.txt" );
double num = 3.1415926;
string str = "abcDEFlmn";
char s[100];
strcpy (s, str.c_str( ));
x.write ((const char *)&num, sizeof(double)); //写入数字 100
x.write (s, strlen(s)); //写入字符串 "abc"
x.close ( ) ;
}
void ReadBiFile( )
{
ifstream y( "d:\\test.txt" );
double num;
char s[100] = "";
y.read(( char *)&num, sizeof(double)); //读取数字
y.read(s, 100 ); //读取字符串
cout << num << ' ' << s;
y.close();
}
int main(){
CreateBiFile ( );
ReadBiFile ( );
return 0;
}
读写示例
int main(){
// 可读可写
fstream x("d:\\test.txt", ios::in|ios::out);
long i, j;
char c1, c2;
// 将前5个字符顺序颠倒
for(i=0,j=4; i