導入
メンバ関数の中で「自分自身」を指したいことがあります。それが this ポインタです。あわせて、「このメンバ関数はメンバを変更しない」と宣言する const メンバ関数を学びます。
説明
this は「今そのメンバ関数を呼び出しているインスタンス自身」を指すポインタです。引数名とメンバ名がぶつかったときの区別などに使います。
#include <iostream>
using namespace std;
class Box {
int width;
public:
Box(int width) {
this->width = width; // this->width はメンバ、width は引数
}
int getWidth() { return width; }
};
int main() {
Box b(50);
cout << b.getWidth() << endl; // 50
return 0;
}
メンバを変更しないメンバ関数には、) の後ろに const を付けます。これで「読み取り専用」と表明でき、const なオブジェクトからも呼べるようになります(const correctness の実践)。
flowchart TB a["int area() const<br/>メンバを変更しない約束<br/>const オブジェクトからも呼べる"] b["void scale(int k)<br/>メンバを変更する(const 付けない)"] a --- b
#include <iostream>
using namespace std;
class Rectangle {
int w, h;
public:
Rectangle(int w, int h) : w(w), h(h) {}
int area() const { // メンバを変更しない → const
return w * h;
}
void scale(int k) { // メンバを変更する → const は付けない
w *= k; h *= k;
}
};
int main() {
const Rectangle r(3, 4); // const オブジェクト
cout << r.area() << endl; // 12(const 関数なので呼べる)
// r.scale(2); // ← エラー(const オブジェクトからは呼べない)
return 0;
}
まとめ
this は自分自身を指すポインタ。値を変更しないメンバ関数には const を付けるのが実務の作法で、getter などは基本 const にします。これで const オブジェクトからも安全に使えます。