ive come to the chapter talking about operator overloading. ive gone through some examples showing a class that adds distances together and a class that adds strings (concatenates the strings together). however, the distance class has the operator function outside the class and the string class has the operator inside the class. does it really matter? i cant figure out the difference and when to use either one. can someone explain?
both classes:
Code:
/////////////////////////////////CLASS DISTANCE////////////
class Distance //english Distance class
{
private:
int feet;
float inches;
public:
Distance() : feet(0), inches (0.0)
{ }
Distance(int ft,float in) : feet(ft),inches(in)
{ }
void getdist() //get length from user
{
cout << "enter feet: "; cin >> feet;
cout << "enter inches: "; cin >> inches;
}
void showdist() //display distance
{ cout << feet << " feet " << inches << " inches" << endl; }
Distance operator + (Distance) const; //add 2 distances
};
//============================================================================================
Distance Distance::operator + (Distance d2) const //return sum
{
int f = feet + d2.inches; //add the feet
float i = inches + d2.inches; //add the inches
if(i >= 12.0)
{
i -= 12.0;
f++;
}
return Distance(f,i);
}
/////////////////////////////CLASS STRING////////////////////////////////
class String
{
private:
enum {SZ = 80}; //size of string object
char str[SZ]; //holds a string
public:
String()
{ strcpy(str,""); }
String(char s[])
{ strcpy(str,s); }
void display() const
{
cout << str;
}
String operator + (String ss) const //add string
{
String temp;
if(strlen(str) + strlen(ss.str) < 20)
{
strcpy(temp.str,str); //copy this string to temp
strcat(temp.str,ss.str); //add at end of string
}
else
{ cout << "\nString overflow"; exit(1); }
return temp; //return temp string
}
};