【C++的取经之路】(七)类的创建及其成员函数、构造函数、析构函数

前言

本文围绕C++类的创建展开介绍。参考《C++ Primer Plus》,本篇文章代码均已测试通过。


一、新建头文件和修改源文件

同样的步骤,先按模版新建Day05.h头文件,定义int Day_05(...) {}函数,后在BasicFunc.h文件中导入,再在main.cpp的程序入口函数main()函数中调用choose()函数。如下就是我们这个LearCpp项目中的最后一步,运行之后可以根据输入的天数(整型数)选择回顾当天的学习内容:

在这里插入图片描述

在这里插入图片描述


二、C++类的创建

废话不多说,直接上代码。

  • 类的创建
/*Day05:
*		1. C++的使用类(类的析构在stock20相关文件中)
*		2. 熟悉vs软件使用
* Larissa857
* 2/9/2025
*/

#pragma once
#include "source.h"

using namespace std;

class Time
{
private:
	int hours;
	int minutes;
public:
	Time();
	Time(int h, int m = 0);
	void AddMin(int m);
	void AddHr(int h);
	void Reset(int h = 0, int m = 0);
	Time operator+(const Time& t) const;		// 运算符重载:operator+()
	Time operator-(const Time& t) const;
	Time operator*(double n) const;
	void Show() const;
};

// 类成员函数
Time::Time()
{
	// 设置默认值
	hours = minutes = 0;
}

Time::Time(int h, int m)
{
	// 初始化赋值
	hours = h;
	minutes = m;
}

void Time::AddMin(int m)
{
	// 计算累计时间分
	minutes += m;
	hours += minutes / 60;
	minutes %= 60;
}

void Time::AddHr(int h)
{
	hours += h;
}

void Time::Reset(int h, int m)
{
	hours = h;
	minutes = m;
}

Time Time::operator+(const Time& t) const
{
	// 运算符+重载,如t3 = t1.operator+(t2) 即 t3=t1+t2
	Time sum;
	sum.minutes = minutes + t.minutes;
	sum.hours = hours + t.hours + sum.minutes / 60;
	sum.minutes %= 60;

	return sum;
}

Time Time::operator-(const Time& t) const
{
	// 运算符-重载
	Time diff;
	int tot1, tot2;
	tot1 = t.minutes + 60 * t.hours;
	tot2 = minutes + 60 * hours;
	diff.minutes = (tot2 - tot1) % 60;
	diff.hours = (tot2 - tot1) / 60;

	return diff;
}

Time Time::operator*(double mult) const
{
	Time result;
	long totalminutes = hours * mult * 60 + minutes * mult;
	result.hours = totalminutes / 60;
	result.minutes = totalminutes % 60;

	return result;
}

void Time::Show() const
{
	cout << hours << " hours, " << minutes << " minutes";
}

// 功能函数
void showmenu_05(void);
void usetime(int isUseTime);		// 调用运算符重载后的类成员函数


int Day_05(...)
{
	int sign;

	cout << "Hello! Welcome to the C++ world——Day05";
	cout << endl;
	cout << "What can I help you?" << endl;
	showmenu_05();
	cin >> sign;

	switch (sign)
	{
	case 0: cout << "【Done】\n"; break;
	case 1: usetime(sign); break;
	case 2: cout << "Nothing to deal with :)\n"; break;
	}

	return 5;
}

void showmenu_05(void)
{
	/*展示功能函数菜单*/
	cout << "Please enter a num from 1 to 11:\n"
		"1) usetime						2) quit\n";
}

void usetime(int isUseTime)
{
	/*调用运算符重载后的类成员函数*/
	cout << "=======UseTime=======" << endl;

	Time weeding(4, 35);
	Time waxing(2, 47);
	Time total;
	Time diff;
	Time adjusted;

	cout << "weeding time = ";
	weeding.Show();
	cout << endl;

	cout << "waxing time = ";
	waxing.Show();
	cout << endl;

	cout << "ToTal Work Time = ";
	total = weeding + waxing;
	total.Show();
	cout << endl;

	diff = weeding - waxing;
	cout << "weeding - waxing = ";
	diff.Show();
	cout << endl;

	adjusted = total * 1.5;
	cout << "adjusted work time = ";
	adjusted.Show();
	cout << endl;
}

  • 类的析构
/*stock20.h
*	定义类及其成员函数
*/


#ifndef STOCK20_H
#define STOCK20_H
#include "source.h"

class Stock
{
private:
	std::string company;
	int shares;
	double share_val;
	double total_val;
	void set_tot() { total_val = shares * share_val; }
public:
	Stock();		// 默认构造
	Stock(const std::string& co, long n = 0, double pr = 0.0);
	~Stock();		// 析构函数
	void buy(long num, double price);
	void sell(long num, double price);
	void update(double price);
	void show() const;			// C风格的类成员函数声明
	const Stock& topval(const Stock& s) const;	// 用于接收最大值的函数指针
};


#endif

/* stock20.cpp
*	以某公司股票为例,分析析构函数、构造函数、类成员函数的作用
*	定义类成员函数、析构函数、构造函数
*/

#include <iostream>
#include "stock20.h"

using namespace std;

// 构造函数
Stock::Stock()
{
	// 设置默认值
	company = "no name";
	shares = 0;
	share_val = 0.0;
	total_val = 0.0;
}

Stock::Stock(const std::string& co, long n, double pr)
{
	// 初始化赋值
	company = co;

	if (n < 0)
	{
		cout << "Number of shares can't be negative; "
			<< company << " shares set to0.\n";
	}
	else
		shares = n;
	share_val = pr;
	set_tot();
}

Stock::~Stock()
{
	// 不作操作,析构函数
}

void Stock::buy(long num, double price)
{
	/*买入/增加持有的股票*/
	if (num < 0)
	{
		cout << "Number of shares purchased can't be negative. "
			<< "Transaction is aborted.\n";
	}
	else
	{
		shares += num;
		share_val = price;
		set_tot();
	}
}

void Stock::sell(long num, double price)
{
	/*卖出/减少持有的股票*/
	if (num < 0)
	{
		cout << "Number of shares sold can't be negative. "
			<< "Transaction is aborted.\n";
	}
	else if (num > shares)
	{
		cout << "You can't sell more than you have! "
			<< "Transaction is aborted.\n";
	}
	else
	{
		shares -= num;
		share_val = price;
		set_tot();
	}
}

void Stock::update(double price)
{
	// 更新现持有股票信息
	share_val = price;
	set_tot();
}

void Stock::show() const
{
	// 输出公司名称、股票信息、股票价格、总值
	using std::ios_base;
	ios_base::fmtflags orig = cout.setf(ios_base::fixed, ios_base::floatfield);
	std::streamsize prec = cout.precision(3);

	cout << "Company: " << company
		<< " Shares: " << shares << '\n';
	cout << " Share Price: $" << share_val;
	cout.precision(2);
	cout << " Total Worth: $" << total_val << '\n';
	cout.setf(orig, ios_base::floatfield);
	cout.precision(prec);
}

const Stock& Stock::topval(const Stock& s) const
{
	if (s.total_val > total_val)
		return s;
	else
		return *this;		// this指针用于替代形如stock1.stock(stock2)中的隐式类名stock1
}
/* usestock20.cpp
*		调用stock类成员函数和析构函数
*/

#include <iostream>
#include "stock20.h"

const int STKS = 4;

int main2()
{
	Stock stocks[STKS] = {
		Stock("NanoSmart", 12, 20.0),
		Stock("Boffo Objects", 200, 2.0),
		Stock("Monolithic Obelisks", 130, 3.25),
		Stock("Fleep Enterprises", 60, 6.5)
	};

	std::cout << "Stock holdings:\n";
	// 寻找最大值,指针加法遍历数组
	int st;
	for (st = 0; st < STKS; st++)
		stocks[st].show();
	const Stock* top = &stocks[0];
	for (st = 1; st < STKS; st++)
		top = &top->topval(stocks[st]);
	std::cout << "\nMost valuable holdings:\n";
	top->show();

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Larissa857

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值