これは私のテストプログラムです。変数s1には、ユーザー定義型のオブジェクトを含むベクトルが含まれています。 < <演算子にこのベクトルをうまく印刷するために、1行に1要素をオーバーロードします。オーバーライドされた演算子からベクトルデータメンバーを反復処理する方法<<
#include <iostream>
#include "myclasses.h"
using namespace std;
int main() {
myclass s1;
s1.add_point(7000, 10);
s1.add_point(8000, 11);
s1.add_point(9000, 12);
cout << s1 << endl;
return 0;
}
ここにクラス定義があります。基本的には、別のユーザー定義オブジェクトの配列です。私は、< <オペレーターに、すべてのエントリーを1行に1つずつ印刷させたいと思います。 "anotherclass"に必要なサポートメソッドがあるとします。
class myclass {
vector<anotherclass> ps;
public:
void add_point(double, double);
friend ostream &operator<<(ostream &out, const myclass &s);
};
void myclass::add_point(double first, double second) {
ps.push_back(anotherclass(first, second));
}
ostream &operator<<(ostream &out, const myclass &s) {
vector<anotherclass>::iterator itr;
vector<anotherclass> psp=s.ps; // Why do I need this? Why can't I use s.ps.begin() and s.ps.end() in the for loop directly?
for (itr=psp.begin() ; itr != psp.end() ; ++itr) {
cout << "(" << itr->get_first() << "," << itr->get_second() << endl;
}
return out;
}
私のプログラムでこれを動作させるには、追加する必要がある行をコメントしました。なぜその線が必要なのか分かりません。誰かが私にそれを説明できますか?
素晴らしい!私は、Bjarneの原理と実践を含む、私が勉強してきたC++に関する2つの巨大な本を持っています。どちらの本もこれを言及していない。 (Bjarneの本には、付録Bの表の定数反復子の記述があります)。他のヒントもありがとう。 –