您的位置:首页 > 其它

058day(自增,自减运算符重载和继承与派生的基本概念)

2017-12-07 23:52 253 查看
172210704111-陈国佳总结《201712月7日》【连续058天】

标题:自增,自减运算符重载和继承与派生的基本概念;

内容:A.自增,自减运算符的重载:

由于自增,自减运算符有前置和后置之分,C++规定:

前置运算符作为一元运算符重载:

成员:T & operator++();   

          T & operator--();

全局:T1 &operator++(T2);

          T2 &operator--(T2);

后置运算符作为二元运算符重载,多写一个没用的参数:

成员:T operator++(int);

          T operatpor--(int);

全局:T1 operator++(T2,int);

          T2 operator--(T2,int);

注:在没有后置重置而前置重置的情况下,vs中,obj++调用前置,dev中,obj++编译出错;

注:我们可以看出++a的返回值是a的引用,所以(++a)=1,a的值变成1,而a++=1出错;

class CDemo{
private :
  int n;
public:
  CDemo(int i=0):n(i){ }
  CDemo & operator++();
  CDemo operator++(int );
 operator int (){ return n;}
 friend CDemo & operator--(CDemo &);
 friend CDemo operator--(CDemo &,int);

};

CDemo & CDemo::operator++()

{                   //前置++ 
++n;
return*this;

}

CDemo CDemo::operator++(int )

{   //后置 ++

    CDemo tmp(*this);
++n;
return tmp; 



CDemo & operator--(CDemo & d)

{
d.n--;
return d;

}

CDemo operator--(CDemo &d,int)

{
CDemo tmp(d);
d.n--;
return tmp;

}

int main()

{
CDemo d(5);
cout<<(d++)<<",";  //d.operator++(0)
cout<<d<<",";
cout<<(++d)<<",";   //d.operator++()
cout<<d<<endl;
cout<<(d--)<<",";   //operator--(d,0)
cout<<d<<",";
cout<<(--d)<<",";  //operator--(d)
cout<<d<<endl;
return 0; 

}



B.继承:一个新类B,与类A相似(B拥有A的全部特点),那么A可作为一个基类,B作为基类的派生类(子类)。

a)派生类是通过对基类进行修改(覆盖)和扩充得到的。

b)派生类一经定义后,可独立使用,不依赖于基类。

c)派生类拥有积累的全部函数和成员变量(无论private,protected,public),但派生类的成员函数不能访问基类中的private成员;

写法:

class 派生类名:public 基类名

{ };

派生类对象的内存空间等于基类对象的体积(存储位置在前)和派生类自己的成员变量体积(在后);

举例:

class CStudent{
private:
    string name;
    string id;
    char gender;
int age;
public:
void PrintInfo();
void SetInfo(const string&name_,const string &id_,int age_,char gender_);
string GetName(){ return name;}

};

class CUndergraduateStudent:public CStudent{
private:
string department;
 //多了系的名称
public:
void PrintInfo(){    //覆盖
CStudent::PrintInfo();
cout<<"Department:"<<department<<endl;

void SetInfo(const string&name_,const string &id_,int age_,char gender_,const string & department_)
{
CStudent::SetInfo(name_,id_,age_,gender_);
department =department_;
}

};

void CStudent::PrintInfo()

{
cout<<"Name:"<<name<<endl;
cout<<"ID:"<<id<<endl;
cout<<"Age:"<<age<<endl;
cout<<"Gender:"<<gender<<endl; 

}

void CStudent::SetInfo(const string&name_,const string &id_,int age_,char gender_)

{
name=name_;id=id_;age=age_;
gender=gender_;

}

int main()

{
CUndergraduateStudent s2;
s2.SetInfo("Potter","1188",19,'M',"Computer Scoence");
cout<<s2.GetName()<<" ";
s2.PrintInfo();
return 0;

}



明日计划:继承关系和复合关系;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: