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 不能(《模板、字符串和异常》一章会讲解模板)。