用char*实现的一个完整的类,包含类的基本操作:一般构造、拷贝构造、赋值转换、重载 > >,< <

一个完整的类,需要有:一般构造函数、拷贝构造函数、赋值函数,涉及数据存储的,还应该对移位运算符进行重载。

同时对一个运算符进行重载及友元重载时,调用顺序为先重载,后友元重载。

#include <iostream.h>
#include <string.h>
#include <stdio.h>

class Person
{
    friend ostream& operator << (ostream& s, const Person& obj);  // declaration of overriding operator << function
    friend istream& operator >> (istream& s, Person& obj);  // declaration of overriding operator >> function

    private:
        char* name;
    public:
        Person (char* n = "")  // default constructor
        {
            name = new char[strlen (n) + 1];
         strcpy (name, n);
        }
        Person (const Person& per) // copy constructor
        {
            name = new char[strlen (per.name) + 1];
            strcpy (name, per.name);
        }
        Person& operator = (const Person& per) //  #1  overriding assignment function 
        {
            if == ( this & per )  // prevent copy itself
                return *this;
            delete[] name;
            name = new char[strlen (per.name) + 1];
            strcpy (name, per.name);
            return *this;
        }
        Person& operator = (char* n) // #2  overriding assignment function - typer conversion
        {
            delete[] name;
            name = new char[strlen (n) + 1];
            strcpy (name, n);
            return *this;
        }
        ~Person () // destructor
        {
            delete[] name;
        }
};
ostream& operator << (ostream& s, const Person& obj) // definition of ...
{
    s << obj.name << endl;
    return s;
}
istream& operator >> (istream& s, Person& obj)   // definition of ...
{
    char cs[128];
    s >> cs;
    if (strlen (obj.name) < strlen (cs))
    {
        delete[] obj.name;
        obj.name = new char[strlen (cs) + 1];
    }
    strcpy (obj.name, cs);
    return s;
}

int main (void)
{
    Person a ("Xiaozhang");  // provoke default constructor
    Person b = "Xiaoli";     // provoke default constructor
    Person c (b);            // provoke copy constructor
    c = a;                   // provoke overriding assignment function - typer conversion
    c = "Laoadfffadfli";     // provoke overriding assignment function - typer conversion
    cin >> b;                // provoke overriding operator >> function - typer conversion
    Person d;
    cin >> d;
    d = d;                    // verify self copy
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值