8 1 class Point private int xcoord int

  • Slides: 27
Download presentation

【例8. 1】重载运算符++。 class Point { private: int xcoord; int ycoord; public: Point (){xcoord =0;

【例8. 1】重载运算符++。 class Point { private: int xcoord; int ycoord; public: Point (){xcoord =0; ycoord =0; } void operator++(){ ++xcoord; ++ ycoord; } };

void main() { Point obj 1; obj 1++; 增加 1 ++obj 1; 增加 2

void main() { Point obj 1; obj 1++; 增加 1 ++obj 1; 增加 2 } //使 xcoord、ycoord

【例8. 2】用友元函数重载运算符++。 #include "iostream. h" class Point { private: int xcoord; int ycoord; public:

【例8. 2】用友元函数重载运算符++。 #include "iostream. h" class Point { private: int xcoord; int ycoord; public:

Point() //无参数构造函数 { xcoord = 0; ycoord=0; } Point(int x, int y) //单一参数构造函数 {

Point() //无参数构造函数 { xcoord = 0; ycoord=0; } Point(int x, int y) //单一参数构造函数 { xcoord = x; ycoord =y; }

void display(){cout<< “(”<< xcoord <<”, ”<<ycoord<<”)”<<endl; } friend Point operator++(Point &); //前缀自增 friend Point

void display(){cout<< “(”<< xcoord <<”, ”<<ycoord<<”)”<<endl; } friend Point operator++(Point &); //前缀自增 friend Point operator++(Point &, int); //后缀自增 };

Point operator++( Point &e) { return Point (++e. xcoord, ++e. ycoord); } Point operator++(

Point operator++( Point &e) { return Point (++e. xcoord, ++e. ycoord); } Point operator++( Point &e, int) { return Point (e. xcoord ++, e. ycoord ++); }

void main() { Point p 1(10, 10), p 2; p 2=p 1++; p 1.

void main() { Point p 1(10, 10), p 2; p 2=p 1++; p 1. display(); p 2=++p 1; p 1. display(); p 2. display(); }

【例8. 3】加法运算符重载 Point: : operator+(Point a) { Point p; //临时对象 p. xcoord= xcoord+ a.

【例8. 3】加法运算符重载 Point: : operator+(Point a) { Point p; //临时对象 p. xcoord= xcoord+ a. xcoord ; p. ycoord= ycoord+ a. ycoord ; return p; //返回临时对象 }

【例8. 4】为字符串重载+运算符。 String: : operator+(String ss) { String temp; //声明一个临时字符串temp strcpy(temp. str, str); //将该字符串复制到temp

【例8. 4】为字符串重载+运算符。 String: : operator+(String ss) { String temp; //声明一个临时字符串temp strcpy(temp. str, str); //将该字符串复制到temp strcat(temp. str, ss. str); //参数字符串相加 return temp; //返回temp字符串 }

按以下方式使用: String s 1 = "Welcome"; String s 2 = "to C++"; String s

按以下方式使用: String s 1 = "Welcome"; String s 2 = "to C++"; String s 3; s 3 = s 1 + s 2;

【例8. 5】重载复合赋值运算符。 void Point: : operator+=(Point a) { xcoord += a. xcoord; ycoord +=

【例8. 5】重载复合赋值运算符。 void Point: : operator+=(Point a) { xcoord += a. xcoord; ycoord += a. ycoord; }

String(char *s = "") { int length = strlen(s); str = new char[length+1]; strcpy(str,

String(char *s = "") { int length = strlen(s); str = new char[length+1]; strcpy(str, s); } ~String() //析构函数 { delete[] str; }

void display() { cout<<str; } };

void display() { cout<<str; } };

void main() { String s 1("Welcome to C++ world n"); String s 2; s

void main() { String s 1("Welcome to C++ world n"); String s 2; s 2 = s 1; s 1. display(); s 2. display(); }