LIFE LOG(ここにはあなたのブログ名)

あつあつ備忘録

ソフトやハード、時にはメカの備忘録をまとめていきます

【C++】オブジェクトのポインタ

f:id:AtsuyaKoike:20190524095847p:plain:w300

オブジェクトのポインタ

  • オブジェクトポインタを使用した演算子は、他のデータ型のポインタ演算と同様に、そのオブジェクト型に関して行われる
  • オブジェクトポインタをインクリメントすると次のオブジェクトを指すようになり、デクリメントするとその逆になる。

study112.cpp

#include <iostream>
using namespace std;

class samp {
    int a, b;
public:
    samp( int n, int m ) {
        a = n;
        b = m;
    }
    int get_a() {
        return a;
    }
    int get_b() {
        return b;
    }
};

int main() {
    samp ob[4] = {
        samp( 1, 2 ),
        samp( 3, 4 ),
        samp( 5, 6 ),
        samp( 7, 8 )
    };

    samp *p;
    p = ob;

    for ( int i = 0; i < 4; ++i ) {
        cout << p->get_a() << ' ';
        cout << p->get_b() << "\n";
        p++;
    }
    
    cout << "\n";
    return 0;
}
$ ./study112 
1 2
3 4
5 6
7 8



Thisポインタ

  • すべてのメンバ関数の呼び出し時に自動的に渡されるポインタで、その呼び出しを行ったオブジェクトを指す
ob.f1();
  • この場合、f1()関数にはobへのポインタが自動的に渡される
  • このポインタをthisという名前で参照する
  • フレンド関数には使用不可

study115.cpp

#include <iostream>
#include <cstring>
using namespace std;

class inventory {
    char item[20];
    double cost;
    int on_hand;
public:
    inventory( char *i, double c, int o ) {
        strcpy( this->item, i );
        this->cost = c;
        this->on_hand = o;
    }
    void show() {
        cout << this->item;
        cout << ":$" << this->cost;
        cout << " 在庫" << this->on_hand << "\n";
    }

};

int main() {
    inventory ob( "レンチ", 4.95, 4 );
    ob.show();
    return 0;
}
$ ./study115 
レンチ:$4.95 在庫4


これは以下のように略して書くこともできる

study114.cpp

#include <iostream>
#include <cstring>
using namespace std;

class inventory {
    char item[20];
    double cost;
    int on_hand;
public:
    inventory( char *i, double c, int o ) {
        strcpy( item ,i );
        cost = c;
        on_hand = o;
    }
    void show() {
        cout << item;
        cout << ":$" << cost;
        cout << " 在庫:" << on_hand << "\n";
    }
};

int main() {
    inventory ob( "レンチ", 9.45, 4 );
    ob.show();
    return 0;
}
$ ./study114 
レンチ:$4.95 在庫4
  • 省略形のほうが楽なので、thisを書く人はいないが、原理を理解しておくことは大切。




引用・参考はこちら

f:id:AtsuyaKoike:20190524100759j:plain:w200
独習C++ 第4版 https://www.amazon.co.jp/dp/4798119768