2.5自定义数据类型
#include <iostream>
using namespace std;
enum GameResult{WIN,LOSE,TIE,CANCEL};
int main(){
GameResult result;
enum GameResult omit=CANCEL;
for(int count=WIN;count<= CANCEL;count++){
result=GameResult(count);
if (result==omit)
cout<<"The game was cancelled "<<endl;
else {
cout<<"The game was played "<<endl;
if(result==WIN)
cout<<"and we won!";
if(result==LOSE)
cout<<" and we lost.";
cout<<endl;
}
}
return 0;
}
运行无错误。
4.2 类
#include <iostream>
using namespace std;
class Clock{
public:
void setTime(int newH=0,int newM=0,int newS=0);
void showTime();
private:
int hour,minute,second;
};
void Clock::setTime(int newH,int newM,int newS){
hour=newH;
minute=newM;
second=newS;
}
inline void Clock::showTime(){
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
int main(){
Clock myClock;
cout<<"First time set and output:"<<endl;
myClock.setTime();
myClock.showTime();
cout<<"Second time set and output:"<<endl;
myClock.setTime(8,30,30);
myClock.showTime();
return 0;
}
第一次运行时定义的时钟没有大写首字母,后面的程序报错没有定义clock,改了以后无运行错误。
4.3 point 类
#include <iostream>
using namespace std;
class point{
public:
point(int xx=0,int yy=0){
x=xx;
y=yy;
}
point (point &p);
int getX(){
return x;
}
int getY(){
return y;
}
private:
int x,y;
};
point ::point(point &p){
x=p.x;
y=p.y;
cout<<"Calling the copy constructor"<<endl;
}
void fun1(point p){
cout<<p.getX()<<endl;
}
point fun2(){
point a(1,2);
return a;
}
int main(){
point a(4,5);
point b=a;
cout<<b.getX()<<endl;
fun1(b);
b=fun2();
cout<<b.getX()<<endl;
return 0;
}
4.4类的组合
在创建对象时既要对本类的基本类型数据成员进行初始化,又要对内嵌对象成员进行初始化。
在提供一个完整的类定义之前,不能定义该类的对象,也不能在内联成员函数中使用该类的对象。
6.6字符串
7.1类的继承与派生
类的继承是新的类从已有类那里得到已有的特性。
一个派生类可以同时有多个基类,这种情况称为多继承。
如果派生类声明了一个和某某基类成员同名的新成员,派生类的新成员就隐藏了外层同名成员。
当类的继承方式为私有继承时,基类中的公有成员都以私有成员身份出现在派生类中,而基类的私有成员在派生类中不可以直接访问。
保护继承中,基类的公有成员和保护成员都以保护成员的身份出现在派生类中,而基类的私有成员不可以直接访问。
派生类的对象可以隐含转换为基类对象。
派生类的对象可以初始化基类的引用。
派生类的指针可以隐含转换为基类的指针。
基类的构造函数和析构函数不能被继承。
构造派生类的对象时,就要对基类的成员对象和新增成员对象进行初始化。
对基类初始化时,需要调用基类的带有形参表的构造函数时,派生类就必须声明构造函数。
兼容性规则例子:
#include <iostream>
using namespace std;
class base1{
public:
void display() const {cout<<"base1::display()"<<endl;}
};
class base2:public base1{
public:
void display() const{cout<<"base2::display()"<<endl;}
};
class derived:public base2{
public:
void display() const{cout<<"derived::display()"<<endl;}
};
void fun(base1 *ptr){
ptr->display();
}
int main(){
base1 base3;
base2 base4;
derived derived1;
fun (&base3);
fun (&base4);
fun (&derived1);
return 0;
}