头文件Stock.h
#ifndef STOCK_H
#define STOCK_H
#include <string>
class Stock{
public:
Stock();
Stock(std::string symbol, std::string name);
std::string getSymbol() const;
std::string getName() const;
double getPreviousClosingPrice() const;
double getCurrentPrice() const;
void setPreviousClosingPrice(double newPreviousPrice);
void setCurrentPrice(double newCurrentPrice);
double getChangePercent() const;
private:
std::string symbol; //stock symbol
std::string name; //stock name
double previousClosingPrice; //stock previous price
double currentPrice; //stock current price
};
#endif // Stock.h
实现文件Stock.cpp
#include "Stock.h"
#include <string>
Stock::Stock() : symbol(""), name(""),
previousClosingPrice(0),
currentPrice(0){
//nothing
}
Stock::Stock(std::string symbol, std::string name){
this->symbol = symbol;
this->name = name;
}
std::string Stock::getSymbol() const{
return symbol;
}
std::string Stock::getName() const{
return name;
}
double Stock::getPreviousClosingPrice() const{
return previousClosingPrice;
}
double Stock::getCurrentPrice() const{
return currentPrice;
}
void Stock::setPreviousClosingPrice(double newPreviousPrice){
previousClosingPrice = newPreviousPrice;
}
void Stock::setCurrentPrice(double newCurrentPrice){
currentPrice = newCurrentPrice;
}
double Stock::getChangePercent() const{
return (currentPrice - previousClosingPrice) / currentPrice;
}
测试文件main.cpp
#include <iostream>
#include <iomanip>
#include "Stock.h"
using namespace std;
int main(){
Stock stock("MSFT", "Microsoft Corporation");
stock.setPreviousClosingPrice(27.5);
stock.setCurrentPrice(27.6);
cout << setw(30) << left << "symbol: " << stock.getSymbol() << endl;
cout << setw(30) << left << "name: " << stock.getName() << endl;
cout << setw(30) << left << "previous closing price: " << stock.getPreviousClosingPrice() << endl;
cout << setw(30) << left << "current price: " << stock.getCurrentPrice() << endl;
cout << setprecision(2); //保留两位小数
cout << setw(30) << left << "change percent: " << stock.getChangePercent() * 100 << "%" << endl;
return 0;
}
运行结果: