C++primer & plus 笔记-----[类]

C++primer & plus 笔记

【两本书一起看的】

第七章 类

自己写的一个类的实现
在这里插入图片描述

Account.hpp

//
//  Account.hpp
//  Step1
//
//  Created by apple on 2020/9/21.
//  Copyright © 2020 apple. All rights reserved.
//

#ifndef Account_hpp
#define Account_hpp
#include <string>
#include <stdio.h>

class  Account
{
    private:
        std::string name;				//储户姓名
        std::string account_number;		//账号
        double money;					//存款
    public:
        Account();						//初始化1
        Account(std::string name_, std::string account_number_);//初始化2
        void show();					//显示储户姓名、账号和存款
        void deposit(double m);		//存入参数指定的存款
        void withdraw(double m);	//取出参数指定的款项
};
#endif /* Account_hpp */

Account.cpp

//  Account.cpp
//  Step1
//
//  Created by apple on 2020/9/21.
//  Copyright © 2020 apple. All rights reserved.
//

#include "Account.hpp"
#include<iostream>

Account::Account()
{
    name = "user";
    account_number = "account_number";
    money = 0.0;
}

Account::Account(std::string name_, std::string account_number_)
{
	name = name_;
    account_number = account_number_;
    money = 0.0;
}
void Account::show()
{
    std::cout << "储户姓名: " << name << std::endl;
	std::cout << "账号: " << account_number << std::endl;
	std::cout << "存款:" << money << std::endl;
}

void Account::deposit(double m)
{
	money += m;
}

void Account::withdraw(double m)
{
	money -= m;
}

main.cpp

//
//  main.cpp
//  Step1
//
//  Created by apple on 2020/9/18.
//  Copyright © 2020 apple. All rights reserved.
#include<iostream>
#include "Stock00.h"
#include "Account.hpp"

int main()
{
    Account act1;
    act1.show();
    Account act2("my account","001");
    act2.show();
    
    act1.deposit(100);
    act1.show();
    
    act2.withdraw(50);
    act2.show();
    
    Account act3 = act2;//拷贝、赋值、析构
    act3.show();

    
    return 0;
}

结果:
在这里插入图片描述

一些小细节:
1.使用class和struct有什么区别?
 唯一区别就是默认的访问权限。使用 class 时,类中的成员默认都是 private 属性的;而使用 struct 时,结构体中的成员默认都是 public 属性的。
 class 继承默认是 private 继承,而 struct 继承默认是 public 继承(《C++继承与派生》一章会讲解继承)。
 class 可以使用模板,而 struct 不能(《模板、字符串和异常》一章会讲解模板)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值