/* C++构造函数和运算符重载程序例案 */ //程序1: #include #include using namespace std; class Person{ string name; bool gender; int age; Person *lover;//注意这里是指针 public: Person(const char *n,bool g) :name(n),gender(g),age(0),lover(NULL){} void show(); void growup(int years); void marry(Person &p); }; void Person::show() { cout<<"大家好,我是"<<(gender?"帅哥":"美女")<name<<’!’<>name>>gender>>age; Person input(name.c_str(),gender);//类似于Person b("春哥",true); input.growup(age); return input; } //输出结果: //大家好,我是美女芙蓉,我今年19岁!目前单身 //春哥和芙蓉结婚 //大家好,我是美女芙蓉,我今年19岁!爱人是春哥 --------------------------------------------------------------------------------------------------------------------------------- //程序2: #include using namespace std; class fraction{ int a; int b; public: fraction(int m=0,int n=1):a(m),b(n){} friend ostream &operator<<(ostream &o,const fraction &f) { o<a) #include using namespace std; class fraction{ int a; int b; public: fraction(int m=0,int n=1):a(m),b(n){} friend ostream &operator<<(ostream &o,const fraction &f) { o<a); } }; fraction operator~(const fraction &f)//因为是非成员函数,所以不需要加”类名::” { return fraction (f.b,f.a); } int main() { fraction f1(0,3); cout< using namespace std; class Stack{ int *a;//指针成员,会动态的指向内存 int max; int len; public: Stack(int n):a(new int[n]),max(n),len(0){} Stack(const Stack& s):a(new int [s.max]),max(s.max),len(s.len){} ~Stack(){delete []a;} Stack& push(const int& m) { if(len>=max) throw 0/*"栈已满!"*/; a[len++]=m; return *this; } void print()const/*加const防止当前对象被修改*/ { for(int i=0;i using namespace std; class F{ int a; int b; public: F(int m=0,int n=1):a(m),b(n){} F &operator++(){a+=b;return *this;}//前++,返回值有引用,新值就作为当前值用,不用copy F operator++(int){F old(*this);a+=b;return old;}//后++,没有引用,用旧值计算并保留旧值,故 //需要copy //注意:重载“<<”(输出运算符)时,如果写成两个参数,就表示不是成员函数,所以必//须加friend,表示友元,才能访问类里面的私有成员,同时第二个参数对于重载后”++” 和”~”的时候必须要加const friend ostream &operator<<(ostream &o,const F &f) { o<