C++捷径之五

来源:互联网 发布:越南废除户籍制度知乎 编辑:程序博客网 时间:2024/05/03 19:45

//  明成函数重运算符

three_d operator=(three_d op2);//类中定义,=运算符重载
three_d three_d::operator ++()//前置++;++a
{
 x++;
 y++;
 z++;
 return *this;
}

three_d operator++(int notused);

three_d three_d::operator ++(int notused)//后置++a++
{
 three_d temp=*this;
 x++;
 y++;
 z++;
 return temp;
}

friend three_d operator++(three_d &op1);//声明为友元,必须加上three_d &op1why?
 friend three_d operator++(three_d &op1, int notused);
//记住

 

friend three_d operator +(three_d op1,three_d op2);// 成员函数定义为友元
three_d operator +(three_d op1,three_d op2)//成员函数此时没有加作用域three_d::
{
 three_d  temp; 
 temp.x=op1.x+op2.x;
 temp.y=op1.y+op2.y;
 temp.z=op1.z+op2.z;
 return temp;
}

 

 

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class sample{
 char *s;
public:
 static int elye;
 sample() { s=new char('/0'); cout<<"Normal constructor."; }
 sample(const sample &ob);
 ~sample() { if(s) delete []s;  cout<<"Freeing s./n";}
 void show() {cout<<s<<'/n';}
 void set( char *str);

 sample operator=(sample &ob);
};

int elye=0;
sample::sample(const sample &ob)
{
 cout<<"Copy constructor./n";
 s=new char[strlen(ob.s)+1];
 strcpy(s, ob.s);
}

void sample::set(char *str)
{
 s=new char[strlen(str)+1];
 strcpy(s, str);
}


sample sample::operator =(sample &ob)
{
 if(strlen(ob.s)>strlen(s))
 {
  delete []s;
  s=new char[strlen(ob.s)+1];
 }

 strcpy(s,ob.s);

 return *this;
}

sample input()
{
 char instr[80];
 sample str;

 cout<<"Enter a string: ";
 cin>>instr;

 str.set(instr);
 return str;
}

int main()
{
 sample ob; 
 ob=input();
 ob.show();

 return 0;
}

//程序没有调试通过,说

//

 

int operator[](int i) { return a[i];}//类中[]说明,数组

ob[2]//等价于ob.operator [](2)

 

three_d operator()(int a,int b,int c);//类中()说明

ob2=ob1(10,11,12);

 

str_type(char *str="") {strcpy(string,str);//类中字符串构造函数

str_type a("Hello ")//定义

 

//--程序#承的使用
class road_vehicle{
};

class truck: public road_vehicle{…};//truckroad_vehicle的派生类。私有不能直接调用

class derived:private base{…};//private派生,则基类中成员均为派生类的私有成员

base::set;//对于基类中定义的set()函数,使之派生类在私有派生情况下仍旧可用

class derived: protected base{…};// protected派生,则基类中成员均为派生类的私有成员

class derived: public base1,public base2{…};//多继承

//派生类的成员若于基类同名,则基于本身。即派生的对派生的,基的对基的

//基于保护的protected,被派生后相当于成为私有变量。

 

//明构造和析构

class base{

//public:

protected:

 base() { cout<<"Constructing base./n"; }

 ~base() { cout<<"Destructing base./n"; }

};

class derived: public base {

public:

 derived() { cout<<"Constructing derived./n"; }

 ~derived() { cout<<"Destructing derived./n"; }

};

int main()

{

 derived ob;

 return 0;

}

//结果:Constructing base.

//         Constructing derived.

//         Destructing derived.

//         Destructing base.

//先调用基类的构造函数,再调用派生类的,析构则相反。

 

//--程序#12  传递参数
 derived(int x, int y): base(y)
{…};//base(y)为基类中定义

 

ob.derived1::i=10;//基类中成员的使用

class derived1: virtual public base{…};//虚基类

 ob.i=10;//此时可以直接调用base中的成员,不需要ob.derived1::i=10