// stock10.h ?Stock class declaration with constructors, destructor added #ifndef STOCK1_H_ #define STOCK1_H_ #include <string> class Stock { private: std::string company; long 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(); // noisy destructor void buy(long num, double price); void sell(long num, double price); void update(double price); void show(); }; #endif
// stock1.cpp ?Stock class implementation with constructors, destructor added #include <iostream> #include "stock1.h" // constructors (verbose versions) Stock::Stock() // default constructor { std::cout << "Default constructor called\n"; company = "no name"; shares = 0; share_val = 0.0; total_val = 0.0; } Stock::Stock(const std::string & co, long n, double pr) { std::cout << "Constructor using " << co << " called\n"; company = co; if (n < 0) { std::cout << "Number of shares can't be negative; " << company << " shares set to 0.\n"; shares = 0; } else shares = n; share_val = pr; set_tot(); } // class destructor Stock::~Stock() // verbose class destructor { std::cout << "Bye, " << company << "!\n"; } // other methods 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() { using std::cout; using std::ios_base; // set format to #.### 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; // set format to #.## cout.precision(2); cout << " Total Worth: $" << total_val << '\n'; // restore original format cout.setf(orig, ios_base::floatfield); cout.precision(prec); } int main() { Stock stock1= Stock("NanoSmart", 12, 20.0); stock1.show(); Stock Stock2("Nano", 120, 40.0); Stock2.show(); Stock Stock3; Stock3.show(); Stock *Stock4 = new Stock("Smart",230,230); Stock4->show(); system("pause"); return 0; }
构造函数中有一类成为默认构造函数,默认构造函数没有参数,因此在声明中不需要对其进行赋值。
当类中没有任何构造函数时,才会去编译默认构造函数。在定义构造函数后,必须也要为类定义默认构造函数,若是未定义默认构造函数,下面代码将会出错。
Stock Stock3;
构造函数的调用提供了两种方式,第一种:显式调用构造函数:
Stock stock1= Stock("NanoSmart", 12, 20.0);
另一种隐式构造函数:
Stock Stock2("Nano", 120, 40.0);