이 내 테스트 프로그램에서 벡터 데이터 멤버를 반복합니다. 변수 s1은 사용자 정의 유형의 객체를 포함하는 벡터를 포함합니다. < < 연산자에이 벡터를 한 줄에 하나씩 멋지게 인쇄하려면 과부하하고 싶습니다.어떻게 재정의 된 연산자 <<
#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;
}
다음은 클래스 정의입니다. 기본적으로 다른 사용자 정의 객체의 배열입니다. < < 연산자를 사용하여 한 줄에 하나씩 모든 항목을 인쇄하고 싶습니다. "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++에 관한 두 권의 책을 읽었습니다. 어떤 책도 이것을 언급하지 않는다. (Bjarne의 저서에는 부록 B에있는 표에서 반복 반복자에 대한 단일 언급이있다). 다른 팁도 주셔서 감사합니다. –