گرانبار کردن عملگر ها برای مقایسه و نمایش دو کلاس در زبان ++c

the_king

مدیرکل انجمن
اگر a را یک شیء از یک کلاس word1 و b را یک شیء از کلاس متفاوت word2 فرض کنیم،
برنامه زیر توانایی های زیر را ارائه می کند :
  • مقدار دهی b را بر اساس مقدار a
  • دریافت مستقیم b از cin
  • ارسال مستقیم a و b به cout
  • مقایسه مقادیر a و b توسط عملگر <
  • ترکیب مقادیر a و b توسط عملگر +

کد:
#include <iostream>

using namespace std;

class word1
{
	private:
		string str;
	public:
		word1(string s)
		{
			str=s;
		}
		operator const char*()
		{
			return str.c_str();
		}	
		friend ostream &operator<<(ostream&,word1&);
};

class word2
{
	private:
		char array[20];
	public:
		word2()
		{
		}
		word2(word1 &w)
		{
			strcpy(array,w);
		}
		int operator >(word1 &w)
		{
			return (strcmp(array,w)>0);
		}
		operator const char*()
		{
			return array;
		}	
		friend istream &operator>>(istream&,word2&);
		friend ostream &operator<<(ostream&,word2&);
};

ostream &operator<<(ostream &output,word1 &w)
{
	output<<w.str.data();
	return output;
}

istream &operator>>(istream &input,word2 &w)
{
	input>>w.array;
	return input;
}

ostream &operator<<(ostream &output,word2 &w)
{
	output<<w.array;
	return output;
}

word1 operator +(string s,word1 w)
{
	string add=s;
	add+=(string)w;
	return word1(add);
}

word1 operator +(word1 &w1,word2 &w2)
{
	string add=(string)w1;
	add+=(string)w2;
	return word1(add);
}

int main()
{
	word1 w1("blank");
	word2 w2(w1),w3;
	cin>>w3;
	if(w3>w1)
		cout<<"start"+w1+w3;
	else
		cout<<"thanks";
	return 0;
}
 

جدیدترین ارسال ها

بالا