LoginSignup
1
0

More than 3 years have passed since last update.

なんで「+」演算子をオーバーロードする時、引数を2つ取る場合メンバ関数として定義できないか。

Posted at

なんで「+」の演算子をオーバーロードする時、引数を2つ取る場合メンバ関数として定義できないか。
下記のようにフレンド関数としてオーバーロードしてはいけるが、、、

class Point {
public:
    int x;
    int y;
    friend Point operator+(int a, Point obj); //引数を2つ取る場合
};

 Point operator+(int a, Point obj) {
     Point ans;

     ans.x = a + obj.x;
     ans.y = a + obj.y;

     return ans;
 }

そこでフレンド関数ではなくて、メンバ関数として定義してみる。

 class Point {
public:
    int x;
    int y;
    Point operator+(int a, Point obj); //コンパイラーに怒られる
};

Point Point::operator+(int a, Point obj) {
     Point ans;

     ans.x = a + obj.x;
     ans.y = a + obj.y;

     return ans;
 }

調べてみると、二項演算子(この場合「+」はこれにあたる)の左側にあるものは暗黙的に*thisポインタが指しているので、1つだけの引数を受け付けるのはメンバ関数の仕様のようだ。

だから文字通り、下記のようにコンパイラーに怒られる。

 error C2804: binary 'operator +' に引数が多すぎます。
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0