#include <iostream> #include <string> using namespace std; class Phone { public: Phone(string name); virtual ~Phone(){cout<<"Phone destory"<<endl;} virtual void print(); string GetName(){return m_name;} private: string m_name; }; Phone::Phone(string name) : m_name(name) { cout<<"Phone create"<<endl; } void Phone::print() { cout<<"phone name:"<<m_name<<endl; } class Iphone:public Phone { public: Iphone(string name, bool IsSiri = 1); ~Iphone(); Iphone(const Iphone& rhs); Iphone& operator=(const Iphone& rhs); virtual void print(); private: bool m_bIsSiri; }; Iphone::Iphone(string name, bool IsSiri) :Phone(name) , m_bIsSiri(IsSiri) { cout<<GetName() + " create"<<endl; } Iphone::Iphone(const Iphone& rhs) :Phone(rhs) //base的copy 函数 { cout<< "copy func"<<endl; m_bIsSiri = rhs.m_bIsSiri; } Iphone& Iphone::operator=(const Iphone& rhs) { cout<< "operator= func"<<endl; Phone::operator=(rhs); //base的赋值操作 m_bIsSiri = rhs.m_bIsSiri; return *this; } Iphone::~Iphone() { cout<<GetName() + " destory"<<endl; } void Iphone::print() { cout<<"i am"<<" " + GetName(); if (m_bIsSiri) { cout<<" and i have siri"<<endl; } else { cout<<" and i have not siri"<<endl; } } int main() { Phone* pPhone = new Iphone("iphone"); pPhone->print(); delete pPhone; pPhone = new Iphone("HTC", 0); pPhone->print(); delete pPhone; pPhone = NULL; Iphone iphone("iphone"); Iphone HTC("HTC"); HTC = iphone;//operator= HTC.print(); Iphone samsung(HTC);//copy构造函数 samsung.print(); return 1; }
时间: 2024-10-07 14:11:00