C++编程(9)

C 编程(9)

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: 查值域(没必要) int i = c1+c2; // i = 64 istream和ostream也依 靠类型转换函数,这使得 我们可以写下面这类语句 while(cin>>x) cout << x; // c1 = c1+c2; // 值域错误:c1不能是64 // // i = c3-64; // i = -4 c2 = c3-64; // 值域错误:c2不能是-4 // // c3 = c4; // 不需要检查值域 // } Beijing University of Posts & Telecommunications Beijing cin>>x返回istream& 这个值被隐式地转换到 一个表明cin状态的值 然后被while检测 但是这类转换丢失了 信息 young@buptnet.edu.cn 11.4.1 歧义性 如果同时存在用户定义转换和用户定义运算 符,那么也可能产生用户定义运算符和内部 运算符之间的歧义性问题 int operator+(Tiny, Tiny); voif f(Tiny t, int i) { t+i; // 错误:歧义,operator+(t,Tiny(i)) 或 int(t)+i ? } // 因此,对于一个类型而言,最好是或者依靠用户定义转换 // 或者依靠用户定义运算符,但不要两者都用 Beijing University of Posts & Telecommunications Beijing young@buptnet.edu.cn 歧义性示例 class X{/*...*/X(int);X(char*);}; class Y{/*...*/Y(int);}; class Z{/*...*/Z(X);}; X f(X); Y f(Y); Z g(Z); void k1() { f(1); // 错误:歧义的f(X(1))或f(Y(1))? f(X(1)); // ok f(Y(1)); // ok g("Mack"); // 错误:需要两次用户定义转换,不会试验g(Z(X("Mack"))) g(X("Doc")); // ok: g(Z(X("Doc"))) g(Z("Suzy"));// ok: g(Z(X("Suzy"))) } Beijing University of Posts & Telecommunications Beijing young@buptnet.edu.cn 歧义性示例 只有在解析一个调用时有需要,才会考虑用 户定义的转换 class XX {/*...*/XX(int); }; void h(double); void h(XX); void k2() { h1(); // 使用h(double(1))还是h(XX(1))? // 结果是调用h(double(1)) }; Beijing University of Posts & Telecommunications Beijing young@buptnet.edu.cn 歧义性示例 class Quad { public: Quad(double); }; Quad operator+(Quad, Quad); void f(double a1, double a2) { Quad r1 = a1+a2; // 双精度加法 Quad r2 = Quad(a1) + a2; // 强制要求Quad算术 } Beijing University of Posts & Telecommunications Beijing young@buptnet.edu.cn 11.5 友元 一个常规的成员函数声明描述了三件...
View Full Document

This note was uploaded on 02/10/2014 for the course ECE C++ taught by Professor Xiaoshengtang during the Fall '13 term at BUPT.

Ask a homework question - tutors are online