명품C++프로그래밍
명품 C++ programming 실습 문제 7장 10번
anycoding
2021. 5. 21. 00:25
반응형
문제
통계를 내는 Statistics 클래스를 만들려고 한다. 데이터는 Statistics 클래스 내부에 int 배열을 동적으로 할당받아 유지한다. 다음과 같은 연산이 잘 이루어지도록 Statistics 클래스와 !, >>, <<, ~연산자 함수를 작성하라.
int main()
{
Statistics stat;
if (!stat) cout << "현재 통계 데이타가 없습니다." << endl;
int x[5];
cout << "5 개의 정수를 입력하라>>";
for (int i = 0; i < 5; i++)cin >> x[i];
for (int i = 0; i < 5; i++)stat << x[i];
stat << 100 << 200;
~stat;
int avg;
stat >> avg;
cout << "avg=" << avg << endl;
}
결과
현재 통계 데이타가 없습니다.
5 개의 정수를 입력하라 >> 1 2 3 4 5
1 2 3 4 5 100 200
avg=45
소스코드
#include<iostream>
using namespace std;
class Statistics {
int* a;
int size=0;
public:
Statistics() { a = new int[10]; size = 0; }
friend bool operator!(Statistics& stat);
friend Statistics& operator<<(Statistics& stat,int x);
friend void operator>>(Statistics& stat,int& avg);
friend void operator~(Statistics& stat);
~Statistics() { delete[]a; }
};
bool operator!(Statistics& stat)
{
if (stat.size == 0) return true;
return false;
}
Statistics& operator<<(Statistics& stat,int x)
{
stat.a[stat.size++] = x;
return stat;
}
void operator>>(Statistics& stat,int& avg)
{
avg = 0;
for (int i = 0; i < stat.size; i++)
avg += stat.a[i];
avg /= stat.size;
}
void operator~(Statistics& stat)
{
for (int i = 0; i < stat.size; i++)
cout << stat.a[i] << ' ';
cout << endl;
}
int main()
{
Statistics stat;
if (!stat) cout << "현재 통계 데이타가 없습니다." << endl;
int x[5];
cout << "5 개의 정수를 입력하라>>";
for (int i = 0; i < 5; i++)cin >> x[i];
for (int i = 0; i < 5; i++)stat << x[i];
stat << 100 << 200;
~stat;
int avg;
stat >> avg;
cout << "avg=" << avg << endl;
}
반응형