C++中构造函数使用

完整的银行账户类及其使用

#include<iostream>
#include<cstring>
using namespace std;

class Account
{
private:
    int ID;
    char Name[20];
    float balance;  //余额
public:
    void Initial(int ID, char Name[], float balance);   //初始化
    int withdraw(float m);  //取出数量为m的钱,返回-1则失败
    void desposits(float m); //存入数量为m的钱
    void showMe(){
        cout << Name << " " << balance << endl;
    }

    //私有变量进行修改
    void setID(int ID){
        ID = this->ID;
    }
    int getID(){
        return ID;
    }
    
    float getBalance(){
        return balance;
    }
    void setBalance(float balance){
        this->balance = balance;
    }
    //修改指针变量值时不允许直接将指针的地址传出
    void setName(char Name[]){
        strcpy(this->Name,Name);
    }
    void getName(char Name[]){
        strcpy(Name,this->Name);
    }


    /*
    //错误直接将指针地址传出。破坏封闭性。
    char *getName(){
        return Name;
    }
    */


    Account(/* args */);    //默认构造函数
    Account(int ID, char Name[], float balance);    //带参构造函数
    Account(Account &other);    //拷贝构造函数
    ~Account();     //析构函数
};

//构造函数无返回值
Account::Account(/* args */)
{
    ID = -1;
    strcpy(Name,"xxxxx");
    balance = 0.0;
}
Account::Account(int ID, char Name[], float balance){
    this -> ID = ID;
    strcpy(this->Name,Name);
    this -> balance = balance;
}
Account::Account(Account &other){
    ID = other.ID;
    strcpy(Name,other.Name);
    balance = other.balance;
}

//析构函数无返回值只有一个
Account::~Account()
{
}

//初始化账户,函数局部变量名和对象变量名重复,调用this指针处理
void Account::Initial(int ID, char Name[], float balance){
    this -> ID = ID;    
    strcpy(this->Name,Name);    //指针赋值
    this -> balance = balance;
}
int Account::withdraw(float m){
    if(balance > m){
        balance = balance - m;
        return 1;
    }else
        return -1;
}
void Account::desposits(float balance){
    this ->balance = this ->balance +balance;
}
int main(){
    char name[] = "Jack";
    Account my(10112,name,600.0);//调用带参构造函数
    my.withdraw(500.0);
    my.showMe();
    Account other(my);//调用拷贝构造函数
    other.showMe();
    Account other2;//调用拷贝构造函数
    other2.showMe();
    other2.setID(11226);
    other2.setName("Abel");
    other2.setBalance(500.0);
    other2.showMe();
    return 0;
}

结果

程序bank_account输出结果

输出结果分析

第一行:利用带参构造函数创建的对象的信息
第二行:利用拷贝构造函数复制第一个对象,而后输出信息
第三行:利用默认构造函数创建的对象的信息
第四行:利用set函数修改第三个对象信息并输出结果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值