(一)基本知识
- //stock00.h
- #ifndef STOCK00_H_
- #define STOCK00_H_
- #include <string>
- class Stock // class declaration
- {
- private:
- std::string company;
- long shares;
- double share_val;
- double total_val;
- void set_tot() { total_val = shares * share_val; }
- public:
- 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();
- }; // note semicolon at the end
- #endif
- #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. ";
- shares = 0;
- }
- 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. ";
- }
- 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. ";
- }
- else if (num > shares)
- {
- cout << "You can't sell more than you have! "
- << "Transaction is aborted. ";
- }
- 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
- << " Shares: " << shares << ' '
- << " Share Price: $" << share_val
- << " Total Worth: $" << total_val << ' ';
- }
1,类的私有成员变量只能通过类的成员函数去访问,类的成员函数可以通过类对象程序访问
2,声明类对象
Stack Jack;
类的每个对象都有自己的存储空间,每个对象都有自己的成员变量,但是多个成员变量共享一份成员函数
(二)类的构造函数和析构函数
- Stock::Stock(const string &co,long n,double pr )
- {
- company = co;
- if (n < 0)
- {
- std::cerr<<"can not be negative";
- shares = 0;
- }
- else
- shares - n;
- share_val = pr;
- set_tot()
- }
构造函数在创建类对象的时候调用,构造函数被用来创建对象,而不能被对象调用
示例:
Stock flood = Stock("hello",4,6.9);
或者 Stock flood("hello",4,6.9);
或者 Stock *pstock = new Stock("hello",4,6.9);
析构函数用来做清理工作
- Stock::~Stock()
- {
- }
(三)类对象可以互相赋值
- Stock Stock1 =Stock("hello",4,6.9);
- Stock Stock2("welcome",4,6.0);
- Stock2 = Stock1;
(四)const成员函数 为了保证成员函数不会修改调用的类对象,C++是将const关键字放在函数括号的后面 void show()const;
(五)this指针 const Stock &topval(const Stock &s)const; 括号内的const是指该函数不会修改被显式的访问的对象 最后面的const是指该函数不会修改被隐式的访问的对象 例:top = Stock1.topval(Stock2); //Stock2被显式访问,Stock1被隐式访问 this指针指向用来调用成员函数的对象,作为隐藏参数传递给函数 示例程序
- const Stock &Stock::topval(const Stock &s)const
- {
- if(s.total_val > total_val)
- {
- return s;
- }
- else
- {
- return *s
- }
- }
(六)类作用域 (1)定义作用域为类的常量
- class Bakery{
- const int months = 12; //出错,因为在声明类的时候类还没有存储空间
- ....
- };
正确的如下:
- class Bakery{
- enum {months = 12}; //出错,因为在声明类的时候类还没有存储空间
- ....
- };
- class Bakery{
- static const int months = 12; //出错,因为在声明类的时候类还没有存储空间
- ....
- };