C++002类的构造函数
类的构造函数专门用于构造新对象、将值赋给他们的数据成员。
// 类定义 // stock00.h #ifndef STOCH00_H_ #define STOCH00_H_ #include<string> using namespace std; class Stock { private: std::string company; long shares; double share_val; double total_val; void set_tot() { total_val = shares * share_val; } // 内联函数 public: Stock(const string & co, long n = 0, double pr = 0.0); // 构造函数 void acquire(const std::string & co, long n, double pr); void buy(long num, double price); void sell(long num, double price); void update(double price); void show(); }; #endif
// 成员函数实现 // stock00.cpp #include<iostream> #include "stock00.h" void Stock::acquire(const std::string & co, long n, double pr) { company = co; if (n < 0) { std::cout << "Number of shares can't be negative;" << company << "shares set to 0.\n"; } else { shares = n; } share_val = pr; set_tot(); } void Stock::buy(long num, double price) { if (num < 0) { std::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) { using std::cout; 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() { std::cout << " Company: " << company<<'\n' << " Shares: $" << shares << '\n' << " Share Price: $" << share_val<<'\n' << " Total Worth: $" << total_val << '\n'; } // 构造函数 Stock::Stock(const string & co, long n, double pr) { company = co; if (n < 0) { std::cerr << "Number of shares can't be negative; " << company << " shares set to 0.\n"; shares = 0; } else { shares = n; } share_val = pr; set_tot(); }
// 类的使用 // usestock0.cpp #include<iostream> #include "stock00.h" int main() { Stock fluffy_the_cat("NanoSmart", 20, 12.50); fluffy_the_cat.show(); return 0; }