1. 程式人生 > 實用技巧 >C++002類的建構函式

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;
}