C++编程(9)

Educn class year int y public explicit yearint iyi

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ,虽然从技术上说它并不是 Beijing University of Posts & Telecommunications Beijing [email protected] 11.3.7 另一些成员函数 为了使得complex更好的工作,还可以定义其他函 数,比如说:检查实部和虚部的值,然后利用这些 函数进行各种有用的运算 class complex{ double re, im; public: double real() const { return re; } double imag() const { return im; } }; inline bool operator==(complex a, complex b) { return a.real()==b.real() && a.imag()==b.imag(); } Beijing University of Posts & Telecommunications Beijing [email protected] 11.3.8 协助函数 将所有的东西集中到一起,complex就变成了 class complex { double re, im; public: complex(double r=0, double i=0) : re(r), im(i) {} double real() const { return re; } double imag() const { return im; } complex& operator+=(complex); complex& operator+=(double); // -=, *=, /= ... }; Beijing University of Posts & Telecommunications Beijing [email protected] 协助函数 除此之外,还必须提供一批协助函数 complex operator+(complex, complex); complex operator+(complex, double); complex operator+(double, complex); // -, *, / ... complex operator+(complex); //一元正号 complex operator-(complex); //一元负号 bool operator==(complex, complex); bool operator!=(complex, complex); istream& operator>>(istream&, complex&); ostream& operator<<(ostream&, complex); // 还可能提供一些以极坐标方式处理复数的函数、数学函数 // 可以参阅标准库的<complex> Beijing University of Posts & Telecommunications Beijing [email protected] 11.4 转换运算符 可以通过构造函数来进行类型转换,但是构造函数 无法刻画 从用户类型到一个内部类型的转换(因为内部类型部 是类) 从新类型到某个已有类型的转换(而不去修改那个已 有类的声明) 这些问题可以通过为源类型定义转换运算符的方式 解决 成员函数X::operator T(),其中T是一个类型 名,定义了一个从X到T的转换 Beijing University of Posts & Telecommunications Beijing [email protected] 转换运算符示例 class Tiny { char v; void assign(int i) { if(i&~077) throw Bad_range(); v = i; } public: class Bad_range{}; Tiny(int i) { assign(i); } Tiny& operator=(int i) { assign(i); return *this; } operator int() const { return v; } // 转换到int的函数 // 注意:int operator int() const { return v; } 是错误的 }; Beijing University of Posts & Telecommunications Beijing [email protected] 转换运算符示例 int main() { Tiny c1 = 2; Tiny c2 = 62; Tiny c3 = c1-c2; // c3 = 60 Tiny c4 = c3; // 不...
View Full Document

Ask a homework question - tutors are online