手写两个类,要体现构造,析构,拷贝构造,赋值,虚函数,重载函数等特点。
以前一直没有认真写过,这次认真写了一下,才发现容易出错的地方真的很多,记录一下。欢迎各位指正。
C++ Code
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
class CLASSBase { public: CLASSBase(); virtual ~CLASSBase();//析构函数 CLASSBase(const string s);//自定义构造函数 CLASSBase(const CLASSBase &);//拷贝构造函数 CLASSBase &operator = (const CLASSBase &);//赋值构造函数 virtual void show() { cout << "Show Base" << endl; } private: int a; string p_data; }; CLASSBase::CLASSBase() { a = 0; p_data = {}; } CLASSBase :: ~CLASSBase() {} CLASSBase::CLASSBase(const string s) { p_data = s; }; CLASSBase :: CLASSBase(const CLASSBase &other) { p_data = other.p_data; } CLASSBase &CLASSBase :: operator = (const CLASSBase &other) { if (this == &other)//自我认证 { return *this; } else { p_data = other.p_data; return *this; } } class DivClass : public CLASSBase { DivClass(); ~DivClass(); DivClass(const string pStr, const string pBase); DivClass(const DivClass &other); DivClass &operator = (const DivClass &other); void show(); private: string pD_data; }; DivClass::DivClass() { pD_data = {}; } DivClass :: ~DivClass() {} DivClass::DivClass(const string pStr, const string pBase) : CLASSBase(pBase) { if (pStr.size() != 0) { pD_data = pStr; } } DivClass::DivClass(const DivClass &other) : CLASSBase(other) { pD_data = other.pD_data; } DivClass &DivClass :: operator =(const DivClass &other) { CLASSBase :: operator =(other);//赋值函数必须显示的调用父类的赋值函数,否则不会去执行父类的赋值函数 if (this == &other) { return *this; } else { pD_data = other.pD_data; return *this; } } void DivClass::show() { cout << "Show Div" << endl; } |