728x90
1.
#include<iostream>
using namespace std;
class Power {
int kick;
int punch;
public:
Power(int kick = 0, int punch = 0) {
this->kick = kick; this->punch = punch;
}
void show();
Power operator+ (Power op2);
Power operator-(Power op3);
};
void Power::show() {
cout << "kick=" << kick << ',' << "punch=" << punch << endl;
}
Power Power::operator+(Power op2){
Power tmp;
tmp.kick = this->kick + op2.kick;
tmp.punch = this->punch + op2.punch;
return tmp;
}
Power Power::operator-(Power op3) {
Power tmp;
tmp.kick = this->kick - op3.kick;
tmp.punch = this->punch - op3.punch;
return tmp;
}
int main() {
Power a(3, 5), b(4, 6), c;
cout << "< 덧셈 >" << endl;
c = a + b;
a.show();
b.show();
c.show();
cout << "< 뺄셈 >" << endl;
c = a - b;
a.show();
b.show();
c.show();
}
2.
#include<iostream>
using namespace std;
class Power {
private:
int kick;
int punch;
public:
Power(int kick = 0, int punch = 0) {
this->kick = kick; this->punch = punch;
}
void show();
Power& operator++();
friend Power operator++(Power &op, int x);
Power& operator+ (int op);
friend Power operator +(int op1, Power op2);
};
void Power::show() {
cout << "kick=" << kick << "," << "punch=" << punch << endl;
}
Power& Power::operator++() {
kick++;
punch++;
return *this;
}
Power operator++(Power &op, int x) {
Power temp = op;
op.kick++;
op.punch++;
return temp;
}
Power& Power::operator+(int op) {
Power temp;
temp.kick = kick + op;
temp.punch = punch + op;
return temp;
}
Power operator+(int op1, Power op2) {
Power temp;
temp.kick = op1 + op2.kick;
temp.punch = op1 + op2.punch;
return temp;
}
int main()
{
Power a(2, 4), b;
b = ++a;
a.show();
b.show();
b = a++;
a.show();
b.show();
b = a + 4;
a.show();
b.show();
a = 2 + b;
a.show();
b.show();
}
반응형
'전공 공부 > C++' 카테고리의 다른 글
클래스 Circle(면적 구하기) (0) | 2020.12.28 |
---|---|
배열 동등 비교 (0) | 2020.12.28 |
클래스 Oval (0) | 2020.12.27 |
클래스 Adder, Calculator 파일 분리 (0) | 2020.12.27 |
클래스 Circle 파일 분리(반지름 입력받아 면적 구하기) (0) | 2020.12.27 |