C++/Overload/Plus

Материал из C\C++ эксперт
Версия от 10:28, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

additional meanings for the + and = operations

  
#include <iostream>  
#include <string.h>  
using namespace std;
class str_type {  
  char string[80];  
public:  
  str_type(char *str = "\0") { strcpy(string, str); }  
     
  str_type operator+(str_type str);  
  str_type operator+(char *str);  
     
  str_type operator=(str_type str);  
  str_type operator=(char *str);  
     
  void show_str(void) { cout << string; }  
} ;  
     
str_type str_type::operator+(str_type str) {  
  str_type temp;  
     
  strcpy(temp.string, string);  
  strcat(temp.string, str.string);  
  return temp;  
}  
     
str_type str_type::operator=(str_type str) {  
  strcpy(string, str.string);  
  return *this;  
}  
     
str_type str_type::operator=(char *str)  
{  
  str_type temp;  
     
  strcpy(string, str);  
  strcpy(temp.string, string);  
  return temp;  
}  
     
str_type str_type::operator+(char *str)  
{  
  str_type temp;  
     
  strcpy(temp.string, string);  
  strcat(temp.string, str);  
  return temp;  
}  
     
main(void)  
{  
  str_type a("Hello "), b("There"), c;  
     
  c = a + b;  
     
  c.show_str();  
  cout << "\n";  
     
  a = "to program in because";  
  a.show_str();  
  cout << "\n";  
     
  b = c = "C++ is fun";  
     
  c = c+" "+a+" "+b;  
  c.show_str();  
     
  return 0;  
}


Define operator +(plus) and cast to double operator

  
#include <iostream>
using namespace std;
class Power {
   double b;
   int e;
   double val;
 public:
   Power(double base, int exp);
   Power operator+(Power obj) {
      double base;
      int exp; 
      base = b + obj.b;
      exp = e + obj.e;
      Power temp(base, exp);
      return temp;
   }
   operator double(void) {return val;}     
};
Power::Power(double base, int exp){
   b = base;
   e = exp;
   val = 1;
   if (exp!=0)
      while(exp-- > 0)
         val *= b;
}
int main(void){
   Power pwr1(4.0, 2);
   double doub1;
   doub1 = pwr1;                
   cout << (doub1 + 100.2) << endl;
   Power pwr2(3.3, 3), pwr3(0,0);
   pwr3 = pwr1 + pwr2;          
   doub1 = pwr3;                
   cout << doub1;
}


Friendly operator+

  
#include <iostream>
#include <string.h>
using namespace std;
class String{
   public:
      String();
      String(const char *const);
      String(const String &);
      ~String();
      char & operator[](int offset);
      char operator[](int offset) const;
      String operator+(const String&);
      friend String operator+(const String&, const String&);
      void operator+=(const String&);
      String & operator= (const String &);
      int GetLen()const { return itsLen; }
      const char * GetString() const { return itsString; }
   private:
      String (int);
      char * itsString;
      unsigned short itsLen;
};
String::String()
{
   itsString = new char[1];
   itsString[0] = "\0";
   itsLen=0;
}
String::String(int len)
{
   itsString = new char[len+1];
   for (int i = 0; i<=len; i++)
      itsString[i] = "\0";
   itsLen=len;
}
String::String(const char * const cString)
{
   itsLen = strlen(cString);
   itsString = new char[itsLen+1];
   for (int i = 0; i<itsLen; i++)
      itsString[i] = cString[i];
   itsString[itsLen]="\0";
}
String::String (const String & rhs)
{
   itsLen=rhs.GetLen();
   itsString = new char[itsLen+1];
   for (int i = 0; i<itsLen;i++)
      itsString[i] = rhs[i];
   itsString[itsLen] = "\0";
}
String::~String ()
{
   delete [] itsString;
   itsLen = 0;
}
String& String::operator=(const String & rhs)
{
   if (this == &rhs)
      return *this;
   delete [] itsString;
   itsLen=rhs.GetLen();
   itsString = new char[itsLen+1];
   for (int i = 0; i<itsLen;i++)
      itsString[i] = rhs[i];
    itsString[itsLen] = "\0";
    return *this;
}
char & String::operator[](int offset)
{
   if (offset > itsLen)
      return itsString[itsLen-1];
   else
      return itsString[offset];
}
char String::operator[](int offset) const
{
   if (offset > itsLen)
      return itsString[itsLen-1];
   else
      return itsString[offset];
}
String String::operator+(const String& rhs)
{
   int  totalLen = itsLen + rhs.GetLen();
   String temp(totalLen);
   int i, j;
   for (i = 0; i<itsLen; i++)
      temp[i] = itsString[i];
   for (j = 0, i = itsLen; j<rhs.GetLen(); j++, i++)
      temp[i] = rhs[j];
   temp[totalLen]="\0";
   return temp;
}
String operator+(const String& lhs, const String& rhs)
{
   int  totalLen = lhs.GetLen() + rhs.GetLen();
   String temp(totalLen);
   int i, j;
   for (i = 0; i<lhs.GetLen(); i++)
      temp[i] = lhs[i];
   for (j = 0, i = lhs.GetLen(); j<rhs.GetLen(); j++, i++)
      temp[i] = rhs[j];
   temp[totalLen]="\0";
   return temp;
}
int main()
{
   String s1("String One ");
   String s2("String Two ");
   char *c1 = { "C-String One " } ;
   String s3;
   String s4;
   String s5;
   cout << "s1: " << s1.GetString() << endl;
   cout << "s2: " << s2.GetString() << endl;
   cout << "c1: " << c1 << endl;
   s3 = s1 + s2;
   cout << "s3: " << s3.GetString() << endl;
   s4 = s1 + c1;
   cout << "s4: " << s4.GetString() << endl;
   s5 = c1 + s2;
   cout << "s5: " << s5.GetString() << endl;
 return 0;
}


friend overloaded + operator

  
#include <iostream>  
using namespace std;  
class Distance{  
   private:  
      int feet;  
      float inches;  
   public:  
      Distance(){ 
         feet = 0; 
         inches = 0.0; 
      }  
      Distance( float fltfeet ){                        
         feet = int(fltfeet);     
         inches = 12*(fltfeet-feet);
      }  
      Distance(int ft, float in){ 
         feet = ft; 
         inches = in; 
      }  
      void showdist(){ 
         cout << feet << "\"-" << inches << "\""; 
      }  
      friend Distance operator + (Distance, Distance); 
};
Distance operator + (Distance d1, Distance d2){  
   int f = d1.feet + d2.feet;        
   float i = d1.inches + d2.inches;  
   if(i >= 12.0){ 
      i -= 12.0; f++;  
   }        
   return Distance(f,i);          
}  
int main(){  
   Distance d1 = 2.5;
   Distance d2 = 1.25;
   Distance d3;  
   cout << "\nd1 = "; 
   d1.showdist();  
   cout << "\nd2 = "; 
   d2.showdist();  
  
   d3 = d1 + 10.0;
   cout << "\nd3 = "; d3.showdist();  
   d3 = 10.0 + d1;
   cout << "\nd3 = "; d3.showdist();  
   cout << endl;  
   return 0;  
}


+ is overloaded for three_d + three_d and for three_d + int.

  
#include <iostream>
using namespace std;
class three_d {
  int x, y, z;
public:
  three_d() { x = y = z = 0; }
  three_d(int i, int j, int k) { x = i; y = j; z = k; }
  // Add two three_d objects together.
  three_d operator+(three_d rh_op);
  // Add an integer to a three_d object.
  three_d operator+(int rh_op);
  // Subtract two three_d objects.
  three_d operator-(three_d rh_op);
  // Overload assignment.
  three_d operator=(three_d rh_op);
  // Overload ==.
  bool operator==(three_d rh_op);
  // Overload - for unary operation.
  three_d operator-();
  // Let the overloaded inserter be a friend.
  friend ostream &operator<<(ostream &strm, three_d op);
  // Let the overloaded + be a friend.
  friend three_d operator+(int lh_op, three_d rh_op);
};
// Overload binary + so that corresponding coordinates are added.
three_d three_d::operator+(three_d rh_op)
{
  three_d temp;
  temp.x = x + rh_op.x;
  temp.y = y + rh_op.y;
  temp.z = z + rh_op.z;
  return temp;
}
// Overload binary + so that an integer can be added to a three_d object.
three_d three_d::operator+(int rh_op)
{
  three_d temp;
  temp.x = x + rh_op;
  temp.y = y + rh_op;
  temp.z = z + rh_op;
  return temp;
}
// Overload binary - so that corresponding coordinates are subtracted.
three_d three_d::operator-(three_d rh_op)
{
  three_d temp;
  temp.x = x - rh_op.x;
  temp.y = y - rh_op.y;
  temp.z = z - rh_op.z;
  return temp;
}
// Overload unary - so that it negates the coordinates.
three_d three_d::operator-()
{
  three_d temp;
  temp.x = -x;
  temp.y = -y;
  temp.z = -z;
  return temp;
}
// Overload assignment for three_d.
three_d three_d::operator=(three_d rh_op)
{
  x = rh_op.x;
  y = rh_op.y;
  z = rh_op.z;
  return *this;
}
// Overload == for a three_d object.
bool three_d::operator==(three_d rh_op)
{
  if( (x == rh_op.x) && (y == rh_op.y) && (z == rh_op.z) )
    return true;
  return false;
}
// These are non-member operator functions.
//
// Overload << as a custom inserter for three_d objects.
ostream &operator<<(ostream &strm, three_d op) {
  strm << op.x << ", " << op.y << ", " << op.z << endl;
  return strm;
}
// Overload + for int + obj.
three_d operator+(int lh_op, three_d rh_op) {
  three_d temp;
  temp.x = lh_op + rh_op.x;
  temp.y = lh_op + rh_op.y;
  temp.z = lh_op + rh_op.z;
  return temp;
}
int main()
{
  three_d objA(1, 2, 3), objB(10, 10, 10), objC;
  cout << "This is objA: " << objA;
  cout << "This is objB: " << objB;
  // Obtain the negation of objA.
  objC = -objA;
  cout << "This is -objA: " << objC;
  // Add objA and objB together.
  objC = objA + objB;
  cout << "objA + objB: " << objC;
  // Subtract objB from objA.
  objC = objA - objB;
  cout << "objA - objB: " << objC;
  // Add obj + int.
  objC = objA + 10;
  cout << "objA + 10: " << objC;
  // Add int + obj.
  objC = 100 + objA;
  cout << "100 + objA: " << objC;
  // Compare two objects.
  if(objA == objB) cout << "objA is equal to objB.\n";
  else cout << "objA is not equal to objB.\n";
  return 0;
}


overloaded "+" operator adds two Distances

  
#include <iostream>
using namespace std;
class Distance
{
   private:
      int feet;
      float inches;
   public:
      Distance() : feet(0), inches(0.0){  }
      Distance(int ft, float in) : feet(ft), inches(in)  {  }
      void getdist(){
         cout << "\nEnter feet: ";  cin >> feet;
         cout << "Enter inches: ";  cin >> inches;
      }
      void showdist() const { cout << feet << "\"-" << inches << "\""; }
      Distance operator + ( Distance ) const;
};
Distance Distance::operator + (Distance d2) const{
   int f = feet + d2.feet;
   float i = inches + d2.inches;
   if(i >= 12.0){
      i -= 12.0;
      f++;
   }
   return Distance(f,i);
}
int main()  {
   Distance dist1, dist3, dist4;
   dist1.getdist();
   Distance dist2(11, 6.25);
   dist3 = dist1 + dist2;
   dist4 = dist1 + dist2 + dist3;
   cout << "dist1 = ";  dist1.showdist(); cout << endl;
   cout << "dist2 = ";  dist2.showdist(); cout << endl;
   cout << "dist3 = ";  dist3.showdist(); cout << endl;
   cout << "dist4 = ";  dist4.showdist(); cout << endl;
   return 0;
}


overloaded "+" operator concatenates strings

  
#include <iostream>
using namespace std;
#include <string.h>
#include <stdlib.h>
class String{
   private:
      enum { SZ=80 };
      char str[SZ];
   public:
      String() { strcpy(str, ""); }
      String( char s[] ) { strcpy(str, s); }
      void display() const { cout << str; }
      String operator + (String ss) const {
         String temp;
         if( strlen(str) + strlen(ss.str) < SZ ){
            strcpy(temp.str, str);
            strcat(temp.str, ss.str);
         }else{
            cout << "\nString overflow"; exit(1);
         }
         return temp;
      }
};
int main(){
   String s1 = "aaa ";
   String s2 = "bbb";
   String s3;
   s1.display();
   s2.display();
   s3.display();
   s3 = s1 + s2;
   s3.display();
   return 0;
}


Overload + for "ob + int" as well as "ob + ob".

  
#include <iostream>
using namespace std;
class MyClass {
  int x, y; 
public:
  MyClass() { 
     x=0; 
     y=0; 
  }
  MyClass(int i, int j) { 
     x=i; 
     y=j; 
  }
  void getXY(int &i, int &j) { 
     i=x; 
     j=y; 
  }
  MyClass operator+(MyClass object2); // ob + ob
  MyClass operator+(int i);         // ob + int
};
// Overload + relative to MyClass class.
MyClass MyClass::operator+(MyClass object2)
{
  MyClass temp;
  temp.x = x + object2.x;
  temp.y = y + object2.y;
  return temp;
}
// Overload + for ob + int
MyClass MyClass::operator+(int i)
{
  MyClass temp;
  temp.x = x + i;
  temp.y = y + i;
  return temp;
}
int main()
{
  MyClass object1(10, 10), object2(5, 3), object3;
  int x, y;
  object3 = object1 + object2;                // add two objects - this calls operator+(MyClass)
  object3.getXY(x, y);
  cout << "(object1+object2) X: " << x << ", Y: " << y << endl;
  object3 = object1 + 100;               // add object + int - this call  operator+(int)
  object3.getXY(x, y);
  cout << "(object1+100) X: " << x << ", Y: " << y << endl;
  return 0;
}


Overloading the + (or any other binary operator) using a friend allows a built-in type to occur on the left or right side of the operator.

  
#include <iostream>  
using namespace std;
class MyClass {  
public:  
  int count;  
  MyClass operator=(int i);  
  friend MyClass operator+(MyClass ob, int i);  
  friend MyClass operator+(int i, MyClass ob);  
};  
     
MyClass MyClass::operator=(int i)  
{  
  count = i;  
  return *this;  
}  
     
// This handles ob + int.  
MyClass operator+(MyClass ob, int i)  
{  
  MyClass temp;  
     
  temp.count = ob.count + i;  
  return temp;  
}  
     
// This handles int + ob.  
MyClass operator+(int i, MyClass ob)  
{  
  MyClass temp;  
     
  temp.count = ob.count + i;  
  return temp;  
}  
     
main(void)  
{  
  MyClass obj;  
  obj = 10;  
  cout << obj.count << " "; 
     
  obj = 10 + obj; 
  cout << obj.count << " "; 
     
  obj = obj + 12; 
  cout << obj.count;
     
  return 0;  
}


overload the "+" operator so that several angles, in the format degrees minutes seconds, can be added directly.

  
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
int totaldegrees, totalminutes, totalseconds;
class angle_value {
 int degrees, minutes, seconds;
 
 public:
 angle_value() {degrees=0,minutes=0, seconds=0;}  // constructor
 angle_value(char *);
 angle_value operator +(angle_value);
};
angle_value::angle_value(char *angle_sum)
{
 degrees=atoi(strtok(angle_sum,"d"));
 minutes=atoi(strtok(0,"m"));
 seconds=atoi(strtok(0,"s"));
}
  
angle_value angle_value::operator+(angle_value angle_sum){
 angle_value ang;
 ang.seconds=(seconds+angle_sum.seconds)%60;
 ang.minutes=((seconds+angle_sum.seconds)/60+ minutes+angle_sum.minutes)%60;
 ang.degrees=((seconds+angle_sum.seconds)/60+ minutes+angle_sum.minutes)/60;
 ang.degrees+=degrees+angle_sum.degrees;
 totaldegrees=ang.degrees;
 totalminutes=ang.minutes;
 totalseconds=ang.seconds;
 return ang;
}
main()
{
 char str1[] = "37d 15m 56s";
 angle_value angle1(str1);   
 
 char str2[] = "10d 44m 44s";
 angle_value angle2(str2);
 
 char str3[] = "75d 17m 59s";
 angle_value angle3(str3);
  
   char str4[] = "130d 32m 54s";
 angle_value angle4(str4);
 
 angle_value sum_of_angles;
 sum_of_angles=angle1+angle2+angle3+angle4;
 cout << "The sum of the angles is " << totaldegrees << "d "
      << totalminutes << "m " << totalseconds << "s"  << endl;
 return (0);
}


Overload the + relative to MyClass.

  
#include <iostream>
using namespace std;
class MyClass {
  int x, y; 
public:
  MyClass() { 
     x=0; 
     y=0; 
  }
  MyClass(int i, int j) { 
     x=i; 
     y=j; 
  }
  void getXY(int &i, int &j) { 
     i=x; 
     j=y; 
  }
  MyClass operator+(MyClass object2);
};
// Overload + 
MyClass MyClass::operator+(MyClass object2)
{
  MyClass temp;
  temp.x = x + object2.x;
  temp.y = y + object2.y;
  return temp;
}
int main()
{
  MyClass object1(10, 10), object2(5, 3), object3;
  int x, y;
  object3 = object1 + object2;     // add two objects - this calls operator+()
  object3.getXY(x, y);
  cout << "(object1+object2) X: " << x << ", Y: " << y << endl;
  return 0;
}


String class with custom +/- operator

   
#include <iostream>
#include <iomanip>
#include <string.h>
using namespace std;
class String 
{
  public: 
    char *operator +(char *append_str)
    { return(strcat(buffer, append_str)); };
   
    char *operator -(char letter);
    String(char *string) 
    { strcpy(buffer, string); 
        length = strlen(buffer); 
    }
    void show_string() { cout << buffer; };
  private:
    char buffer[256];
    int length;
};
int main(void){
   String title("A");
   title = title + "Programmer"s Bible\n";
   title.show_string();
}