环境: ubuntu

编译器:  g++

 

学习C++,首先要学习类的使用,下面的代码,包含了私有成员、共有成员的使用,话不多说,我们先跑起来。

 

创建 stock00.h  文件

#ifndef STOCK00_H_
#define STOCK00_H_

#include <string.h>

class Stock
{
private:
        std::string m_company;
        long m_shares;
        double m_share_val;
        double m_total_val;
        void set_tot();
public:
        Stock();
        ~Stock();
    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"

//构造函数
Stock::Stock()
{
  m_company = "huawei";
  m_shares = 100;
  m_share_val = 5.4;
  set_tot();
}

//析构函数
Stock::~Stock()
{

}

inline void Stock::set_tot()
{
    m_total_val = m_shares * m_share_val;
}

void Stock::acquire(const std::string & co, long n, double pr)
{
        m_company = co;
    if(n < 0)
    {
                std::cout << "Number of shares can't be negative; " << m_company << " shares set to 0 \n";
                m_shares = 0;
    }
    else
    {
                m_shares = n;
    }
        m_share_val = pr;
    set_tot();
}

void Stock::buy(long num, double price)
{
    if(num < 0)
    {
        std::cout << "Number of shares can't be negative; " <<  "Transaction is aborted.\n";
    }
    else
    {
                m_shares += num;
                m_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 > m_shares)
    {
        cout << "You can't sell more than you have!" <<  "Transaction is aborted.\n";
    }
    else
    {
                m_shares -= num;
                m_share_val = price;
        set_tot();
    }
}

void Stock::update(double price)
{
        m_share_val = price;
    set_tot();
}

void Stock::show()
{
        std::cout << "Company: " << m_company
                  << "   Shares:" << m_shares << '\n'
                  << "   Share price: $" << m_share_val
                  << "   Total worth: $" << m_total_val << '\n';
}


int  main()
{
      Stock a;
        //a.sales = 3;  此行是错误的,私有成员是无法直接赋值的,只能通过成员函数赋值。

        a.show();
        a.buy(20, 2.8);
        a.show();
        a.sell(30, 3.0);
        a.show();

        return 0;
}

 

编译:

  

g++ stock00.cpp -o test

 

运行:

./test

 

运行结果:

 

【C++入门课程一】类的私有成员、共有成员_g++

 

Talk is cheap, show me the code