<<演算子のオーバーロード
rhs、lhsででてきた複素数(Complex)クラスに、挿入演算子を定義してみました。まず、クラス定義
// Complex.h class Complex { public: Complex (int real = 0, int img = 0); friend Complex operator+ (Complex lhs, Complex rhs); friend std::ostream &operator<< (std::ostream& o, Complex& c); private: int real, img; };
次に実装コードです。
// Complex.cpp: Complex クラスのインプリメンテーション // ////////////////////////////////////////////////////////////////////// #include "CPP6.h" #include "Complex.h" ////////////////////////////////////////////////////////////////////// // 構築/消滅 ////////////////////////////////////////////////////////////////////// Complex::Complex (int real, int img) { this->real = real; this->img = img; } Complex operator + (Complex lhs, Complex rhs) { return Complex (lhs.real + rhs.real, lhs.img + rhs.img); } std::ostream& operator<< (std::ostream& o, Complex& c) { return o << c.real << "+" << c.img << "i"; }
CPP6.hは#include <iostream>
って書いてあるだけです。あと、main関数を追加して、ビルドしてみます。
// CPP6.cpp #include "CPP6.h" #include "Complex.h" using namespace std; int main (void) { Complex A (3, 2), B (5, 6), C; C = A + B; cout << A << " + " << B << " = " << C << endl; return 0; }
--------------------構成: CPP6 - Win32 Debug-------------------- コンパイル中... Complex.cpp C:\work\CPP6\Complex.cpp(39) : error C2248: 'real' : private メンバ (クラス 'Complex' で宣言されている)にアクセスできません。 c:\work\cpp6\complex.h(28) : 'real' の宣言を確認してください。 C:\work\CPP6\Complex.cpp(39) : error C2248: 'img' : private メンバ (クラス 'Complex' で宣言されている)にアクセスできません。 c:\work\cpp6\complex.h(28) : 'img' の宣言を確認してください。 CPP6.cpp cl.exe の実行エラー CPP6.exe - エラー 2、警告 0
あれれ。[原因不明]挿入子の定義と宣言を同時に行うとエラーにもありますが、VC++で<<演算子のオーバーロードはこういうエラーになるらしい。一応、現在のところ下のものが解となるようです。つまり、宣言と同時に定義を行うと、エラーになりません。
// Complex.h class Complex { public: Complex (int real = 0, int img = 0); friend Complex operator+ (Complex lhs, Complex rhs); friend std::ostream &operator<< (std::ostream& o, Complex& c) { return o << c.real << "+" << c.img << "i"; } private: int real, img; };
他のコンパイラは?時間ができたら試してみます。
トラックバック
- このエントリーにトラックバック:
- http://frog.raindrop.jp/cgi-bin/mt/mt-tb.cgi/221
コメント