前言
数据类型决定了程序中数据和操作的意义。
i = i + j;
如果i,j是整型int数据,那么这条语句执行普通的加法运算。
C++的目标之一是让用户使用自定义数据类型就像使用基本数据类型一样。
类
类是一种将抽象转换为用于自定义类型的C++工具,它将数据表示和数据操纵方法组合成一个简洁的包。
例如,一个股票类的数据表示和数据操作方法如下:
类的声明
#ifndef PROJECT1_SHARE_H
#define PROJECT1_SHARE_H
#include <array>
using namespace std;
class Share {
private:
string company;
long shares;
double share_value;
double total_value;
void set_total(){
total_value = shares * share_value;
}
public:
void acquire(
const string &comp ,
long number ,
double price);
void buy(
long number ,
double price);
void sell(
long number ,
double price);
void update(
double price);
void show();
};
#endif //PROJECT1_SHARE_H
类名首字母需要大写,这是一个不成文的规定!class关键字指出代码设计一个类。关键字private(默认)和关键字public描述了对类成员的访问控制。
通常将数据成员放在private部分,组成类接口的成员函数放在public部分。类的对象可以直接访问public部分,但是只能通过public成员函数来访问private数据成员。
类的定义
#include <iostream>
#include "Share.h"
void Share::acquire(
const string &comp,
long number,
double price) {
company = comp;
if (number <
0){
cout <<
"The number of shares purchased can not be less than zero, the transaction canceled!" << endl;
shares =
0;
}
else
shares = number;
share_value = price;
set_total();
}
void Share::buy(
long number,
double price) {
if (number <
0){
cout <<
"The number of shares purchased can not be less than zero, the transaction canceled!" << endl;
}
else{
shares += number;
share_value = price;
set_total();
}
}
void Share::sell(
long number,
double price) {
if (number <
0){
cout <<
"The number of shares sold can not be less than zero, the transaction canceled!" << endl;
}
else if (number > shares){
cout <<
"The number of shares sold can not be greater than the number of existing shares, the transaction canceled!" << endl;
}
else{
shares -= number;
share_value = price;
set_total();
}
}
void Share::update(
double price) {
share_value = price;
set_total();
}
void Share::show() {
cout <<
"Company Name: " << company << endl;
cout <<
"Number of shares held:" << shares << endl;
cout <<
"Stock price:" << share_value << endl;
cout <<
"Total stock:" << total_value << endl;
}
定义成员函数时,使用作用域解析运算符::来标识函数所属的类。类方法可以访问类的private组件。
类的使用
#include <iostream>
#include <string>
#include "cmake-build-debug/Share.h"
using namespace
std
int main() {
Share xiong
xiong
.acquire(
"lenovo" ,
100 ,
16.6)
xiong
.show()
xiong
.buy(
100 ,
18.8)
xiong
.show()
xiong
.sell(
10000 ,
21.6)
xiong
.show()
xiong
.buy(
30000,
28.6)
xiong
.show()
xiong
.sell(
30000 ,
1.6)
xiong
.show()
}
测试结果
Company Name:
lenovo
Number of shares held:100
Stock price:16.6
Total stock:1660
Company Name:
lenovo
Number of shares held:200
Stock price:18.8
Total stock:3760
The number of shares sold can not be greater than the number of existing shares,
the transaction canceled!
Company Name:
lenovo
Number of shares held:200
Stock price:18.8
Total stock:3760
Company Name:
lenovo
Number of shares held:30200
Stock price:28.6
Total stock:863720
Company Name:
lenovo
Number of shares held:200
Stock price:1.6
Total stock:320
转载请注明原文地址: https://ju.6miu.com/read-7565.html