オーバーロードされた代入演算子で作成されたペアのリストをどのように出力することができますか?C++ペアのリストを出力する(オーバーロードされた演算子で作成)
私がすでに試したことは、ここに見られるように、配列(したがってlist1 [5])を作成し、それに値を割り当てることです。しかし、ループを使ってすべての要素を個別に印刷する必要があるので、5組の数字のセット全体を印刷する最良の方法のようには思えません。
このプロジェクトは、もともとはリンクされたリスト機能を持っていましたが、関連性の有無はわかりませんので省略しましたが、リストを印刷する必要があると思われます。私は、すべての要素を手動で印刷する以外に何ができるかについての洞察を非常に高く評価しています。
Pair.h:
#ifndef PAIR_H
#define PAIR_H
#include <iostream>
using namespace std;
class Pair
{
friend ostream& operator<<(ostream& out, const Pair& p);
public:
Pair();
Pair(int firstValue, int secondValue);
~Pair();
void setFirst(int);
void setSecond(int);
int getFirst() const;
int getSecond() const;
private:
int first;
int second;
};
#endif
Pair.cpp
#include "Pair.h"
//friend function
ostream& operator<<(ostream& out, const Pair& p)
{
out << "(" << p.first << "," << p.second << ")";
return out;
}
Pair::Pair()
{
first = 0;
second = 0;
}
Pair::Pair(int firstValue, int secondValue)
{
first = firstValue;
second = secondValue;
}
Pair::~Pair(){ }
void Pair::setFirst(int newValue)
{
first = newValue;
}
int Pair::getFirst() const
{
return first;
}
void Pair::setSecond(int newValue)
{
second = newValue;
}
int Pair::getSecond() const
{
return second;
}
MAIN.CPP
#include "Pair.h"
#include <iostream>
using namespace std;
void testPair();
int main()
{
testPair();
cout << endl;
cout << endl;
system("Pause");
return 0;
}
void testPair()
{
// Create your own testing cases after adding the class Pair.
Pair list1[5], list2, list3;
list1[1].setFirst(10);
list1[1].setSecond(11);
cout << "TEST: Pair <<\n\n";
cout << "\tList1 is: " << list1[1] << endl;
// NOTE: Do NOT make your class Pair a template.
}
ここで私がした場合にのみ印刷(10、11)だろうが、私はこのメソッドに固執する場合は、手動でそれらのすべてを印刷する必要があるだろうリストに追加ペアを追加します。
ありがとうございました!私はそれを働かせようとします。 – BaloneyOs