ورود

View Full Version : سوال: فهم عملگر مجدد



mohammad1993
سه شنبه 07 شهریور 1391, 17:49 عصر
سلام دوستان .برنامه ای که نوشتم برای فهمیدن تعریف عملگر مجدد هست.نمی دونم درست نوشتم یا نه.لطفا کمکم کنید که مشکلی داره یانه.اگر من i,j در private قرار بدم چجوری می تونم i,j رو در تابع operator قابل دسترس کنم؟برای اجرای برنامه چی کار کنم؟
#include <iostream.h>
#include <conio.h>
class topic
{
public:
void func1();
void func2();
void print();
topic operator+();
int i,j;
}obj1,obj2,r;
void topic::func1()
{
cout<<"enter number 1:\t"<<endl;
cin>>i;
}
void topic::func2()
{
cout<<"enter number 2:\t "<<endl;
cin>>j;
}
topic operator+(topic obj1,topic obj2)
{
topic r;
r.i=obj1.i+obj2.i;
r.j=obj1.j+obj2.j;
return r;
}
void topic::print()
{
cout<<"number 1:\t"<<i<<endl;
cout<<"number 2:\t"<<j<<endl;
}
int main()
{
topic r;
cout<<"wellcome to the my plan"<<endl;
do
{
cout<<"order from obj1"<<endl;
obj1.func1();
obj1.func2();
obj1.print();
cout<<"order from obj2"<<endl;
obj2.func1();
obj2.func2();
obj2.print();
cout<<"sum of them:\t"<<endl;
obj1=obj1 + obj2;
obj1.print();
cout<<endl<<"thank you "<<endl;
getch();
}
while(true);
return 0;
}

hadi0x7c7
سه شنبه 07 شهریور 1391, 22:07 عصر
این فکر کنم بهتر باشه:
#include <iostream>
using namespace std;

class topic {
public:
void func1();
void func2();
void print();
topic operator+(topic other);
private:
int i, j;
} obj1, obj2, r;
void topic::func1() {
cout << "Enter i:";
cin >> i;
}
void topic::func2() {
cout << "Enter j:";
cin >> j;
}
topic topic::operator+(topic obj2) {
topic r;
r.i = i + obj2.i;
r.j = j + obj2.j;
return r;
}
void topic::print() {
cout << "i: " << i << endl;
cout << "j: " << j << endl;
}
int main() {
topic r;
cout << "wellcome to the my plan" << endl;
while (true) {
cout << "order from obj1" << endl;
obj1.func1();
obj1.func2();
obj1.print();
cout << "order from obj2" << endl;
obj2.func1();
obj2.func2();
obj2.print();
cout << "sum of them:\t" << endl;
obj1 = obj1 + obj2;
obj1.print();
cout << endl << "thank you " << endl;

}
return 0;
}