拷贝构造函数习题

Bank.h


#pragma once
#include
using namespace std;

class Bank
{
public://构造函数和析构函数
    Bank();//构造函数
    Bank(int balance);
    Bank(int balance, char *name);
    Bank(const Bank &p);//拷贝构造函数
    ~Bank();//析构函数
public://运算符重载
    bool operator<(const Bank &p);
    bool operator==(const Bank &p);
    Bank& operator=(const Bank &p);
public://行为
    void save(int money);
    void draw(int money);
    void show();
public://工具
    char *getName();
    void setName(char *name);
private://数据
    char *m_name;
    int m_balance;
};


Bank.cpp

#include "stdafx.h"
#include "Bank.h"
using namespace std;

//析构和构造函数

//默认构造函数
Bank::Bank()
{
    m_name = new char[1];
    *m_name = '\0';
    m_balance = 0;
    cout << "默认构造函数" << endl;
}

Bank::Bank(int balance, char *name){
    m_balance = balance;
    m_name = new char[strlen(name) + 1];
    sprintf_s(m_name,(strlen(name)+1),name);
    cout << m_name << "构造函数" << endl;
}
Bank::Bank(const Bank &p){
    
    if (p.m_balance >= 0 && p.m_name != NULL)
    {
        m_name = new char[(strlen(p.m_name) + 1)];
        sprintf_s(m_name, strlen(p.m_name) + 1, p.m_name);
        m_balance = p.m_balance;
    }
    else {
        m_balance = 0;
        m_name = new char[1];
        *m_name = '\0';
    }
    cout << m_name << "初始化拷贝构造函数" << endl;
    
}

Bank::~Bank()
{
    delete[] m_name;
    m_name = NULL;
}

//行为
void Bank::save(int money){
    m_balance += money;
    cout << m_name << "存入:" << money << "余额:" << m_balance << endl;
}
void Bank::draw(int money){
    m_balance -= money;
    cout << m_name << "取出:" << money << "余额:" << m_balance << endl;
}
void Bank::show(){
    cout << m_name << "账户余额:" << m_balance << endl;
}

//工具
char * Bank::getName(){
    //cout << *m_name << endl;
    return m_name;
}
void Bank::setName(char *name){
    if (m_name)
    {
        delete[] m_name;
    }
    if (name==NULL)
    {
        m_name = new char[1];
        *m_name = '\0';
    } else {
        m_name = new char[strlen(name) + 1];
        strcpy_s(m_name,strlen(name)+1,name);
    }
    m_name = name;
}

main.cpp

// 构造析构函数23期92子羽.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "Bank.h"

int _tmain(int argc, _TCHAR* argv[])
{
    Bank icbc(2000,"ICBC");
    icbc.save(1000);
    icbc.draw(1000);
    icbc.show();

    cout << "+++++++++++++++++++" << endl;

    //Bank icbc2 = icbc;
    Bank icbc2(icbc);
    icbc2.save(100);
    icbc2.draw(1700);
    icbc2.show();

    cout << "===================" << endl;

    Bank *abc = new Bank(4000,"ABC");
    abc->save(1000);
    abc->draw(3000);
    abc->show();
    

    cout << "<<<<<<<<<<<<<<<<<<" << endl;

    Bank *abc2 = new Bank((*abc));
    abc2->save(100);
    abc2->draw(1900);
    abc2->show();

    delete abc;
    abc = NULL;
    delete abc2;
    abc2 = NULL;



    return 0;
}


你可能感兴趣的:(拷贝构造函数习题)