c++的this指针和对象数组

来源:互联网 发布:ipad4软件更新打不开 编辑:程序博客网 时间:2024/05/01 23:38

1.每个成员函数(包括构造函数和析构函数)都有一个this指针,this指针指向当前调用对象。如果需要调用整个对象,则使用*this,*this表示整个对象。

 

2.对象数组

   ●对象数组的定义

Stock flutty[4];
   ●对象数组的初始化

Stock flutty[4]; //此时调用默认构造函数进行初始化
Stock stocks[3] = {    Stock("Nano", 123, 12.3),    Stock("Boffo", 233, 11.2),    Stock("Fleep", 456, 13.8)}; //调用构造函数进行初始化
3.this指针使用实例:

下例使用this指针比较对象数组中价格这个成员的大小

文件结构:


stock20.h代码:

#ifndef STOCK10_H_INCLUDED#define STOCK10_H_INCLUDED#include <string>using namespace std;class Stock{    private:        string company;        long shares;        float price;        float total;        void setTotal()        {            total = shares * price;        }    public:        Stock();  //默认构造函数        Stock(const string & comp, long shar, float pric); //构造函数        ~Stock();  //析构函数        void buy(long shar, float pric);        void sell(long shar, float pric);        void show();        const Stock & topVal(const Stock & s) const;};#endif // STOCK10_H_INCLUDED
stock20.cpp代码:

#include <iostream>#include "stock20.h"using namespace std;Stock::Stock()            //定义默认构造函数{    company = "No name";    shares = 0;    price = 0.0;    setTotal();}Stock::Stock(const string & comp, long shar, float pric)  //定义构造函数{    company = comp;    shares = shar;    price = pric;    setTotal();}Stock::~Stock()       //析构函数{}void Stock::buy(long shar, float pric){    if(shar < 0)        cout << "Cannot buy a nagitive number of shares.\n";    else        shares += shar;    price = pric;    setTotal();}void Stock::sell(long shar, float pric){    if(shar < 0)        cout << "Cannot sell a nagitive number of shares.\n";    else if(shares < shar)        cout << "Cannot sell a larger number of shares.\n";    else        shares -= shar;    price = pric;    setTotal();}void Stock::show(){    cout << "Company : " << company << endl;    cout << "Shares : " << shares << endl;    cout << "Price : " << price << endl;    setTotal();    cout << "Total : " << total << endl << endl;}const Stock & Stock::topVal(const Stock & s) const{    if(s.total > total)        return s;    else        return *this;   //返回当前对象}
main.cpp代码:

#include <iostream>#include "stock20.h"using namespace std;int main(){    int i;    Stock flutty[4];    for(i = 0; i < 4; i++)        flutty[i].show();    for(i = 0; i < 4; i++)        flutty[i].buy(1000 * i, 12.3 * i);    for(i = 0; i < 4; i++)        flutty[i].show();    Stock top;    top = flutty[0];    for(i = 1; i < 4; i++)        top = top.topVal(flutty[i]);           //调用topVal函数进行比较大小    cout << "The highest price shares is \n";    top.show();    return 0;}Stock stocks[3] = {    Stock("Nano", 123, 12.3),    Stock("Boffo", 233, 11.2),    Stock("Fleep", 456, 13.8)};
运行结果:






0 0
原创粉丝点击