Figure called Rectangle called Triangle called include iostream

  • Slides: 52
Download presentation

Figure called! Rectangle called! Triangle called!

Figure called! Rectangle called! Triangle called!

加法运算符重载的方法和规则 #include <iostream> using namespace std; class Complex { public: Complex(double r=0. 0, double

加法运算符重载的方法和规则 #include <iostream> using namespace std; class Complex { public: Complex(double r=0. 0, double i=0. 0) { real=r; imag=i; } Complex Add(Complex &c); // 复数的加法运算 Complex Sub(Complex &c); // 复数的减法运算 void display(); // 复数输出 private: double real; double imag; };

Complex: : Add(Complex &c) { return Complex(real+c. real, imag+c. imag); } Complex: : Sub(Complex

Complex: : Add(Complex &c) { return Complex(real+c. real, imag+c. imag); } Complex: : Sub(Complex &c) { return Complex(real-c. real, imag-c. imag); } void Complex: : display() { cout<<"("<<real<<", "<<imag<<")"<<endl; }

例exam 12 -6 输入运算符的重载 #include <iostream. h> class Point { public: Point(int i=0, int

例exam 12 -6 输入运算符的重载 #include <iostream. h> class Point { public: Point(int i=0, int j=0) { x=i; y=j; } //<<、>>必须友元重载 friend istream &operator>>(istream &in, Point &a); private: int x, y; }; istream &operator>>(istream &in, Point &a) { int main() cout<<"Enter the x and y : "; { in>>a. x; Point a(10, 10); in>>a. y; cin>>a; return in; return 0; } }

o o o o o #include <iostream. h> class Point { public: Point(int i=0,

o o o o o #include <iostream. h> class Point { public: Point(int i=0, int j=0) { x=i; y=j; } friend istream &operator>>(istream &in, Point &a); friend ostream &operator<<(ostream &out, Point &a); private: int x, y; }; istream &operator>>(istream &in, Point &a) { cout<<"Enter the x and y : "; in>>a. x; in>>a. y; return in; }

o ostream &operator<<(ostream &out, Point &a) o { o out<<a. x<<", "<<a. y<<endl; o

o ostream &operator<<(ostream &out, Point &a) o { o out<<a. x<<", "<<a. y<<endl; o return out; o } o int main() o { o Point a(10, 10); o cout<<a; o cin>>a; o cout<<a; o return 0; o }

向量类模板定义 template<class T> class Vector { T *data; int size; public: Vector(int i) {

向量类模板定义 template<class T> class Vector { T *data; int size; public: Vector(int i) { data=new T[i]; } ~Vector() { delete[] data; } T &operator[](int i) { return data[i]; } };

3) 从普通类派生出类模板 [例]: class Base { …… }; template <class T> class Derived: public

3) 从普通类派生出类模板 [例]: class Base { …… }; template <class T> class Derived: public Base { T data; …… }