首页 > 其他 > 详细

命名空间里的运算符

时间:2015-04-14 00:19:22      阅读:163      评论:0      收藏:0      [点我收藏+]

考虑二元运算符@,如果x的类型为X,而y的类型是Y,x@y将按如下方式解析:

--若X是类,查询作为X的成员函数或者X的某个基类的成员函数的operator@。

--在围绕x@y的环境中,查询operator@的声明。

--若X在命名空间N里定义,在N里查询operator@的声明。

--在Y在命名空间M里定义,在M里查村operator@的声明。

技术分享
 1 #include <iostream>
 2 using namespace std;
 3 
 4 class X {
 5 public:
 6     void operator+(int) {
 7         cout << "from class X" << endl;
 8     }
 9 };
10 
11 int main() {
12     X x;
13     x + 1;    // from class X
14 
15     return 0;
16 }
For Item 1

 

技术分享
 1 #include <iostream>
 2 using namespace std;
 3 
 4 class X {
 5 public:
 6 };
 7 
 8 class Y {
 9 public:
10 };
11 
12 
13 int main() {
14     X x;
15     Y y;
16 
17     void operator+(X& x, Y& y);
18 
19     x + y;    // from function
20 
21     return 0;
22 }
23 
24 void operator+(X& x, Y& y) {
25     cout << "from function" << endl;
26 }
For Item 2

 

技术分享
 1 #include <iostream>
 2 using namespace std;
 3 
 4 namespace NX {
 5     class X {
 6     public:
 7         /*void operator+(int) {
 8             cout << "from class X" << endl;
 9         }*/
10     };
11 
12     void operator+(X& x, int) {
13         cout << "form namespace NX" << endl;
14     }
15 }
16 
17 int main() {
18     NX::X x;
19     x + 1;    // from namespace NX
20 
21     return 0;
22 }
For Item 3

 

技术分享
 1 #include <iostream>
 2 using namespace std;
 3 
 4 class X {
 5 public:
 6 };
 7 
 8 namespace NY {
 9     class Y {
10     public:
11     };
12 
13     void operator+(X& x, Y& y) {
14         cout << "from namespace NY" << endl;
15     }
16 }
17 
18 int main() {
19     X x;
20     NY::Y y;
21 
22     x + y;    // from namespace NY
23 
24     return 0;
25 }
For Item 4

 

参考: TC++PL P237

命名空间里的运算符

原文:http://www.cnblogs.com/wuhanqing/p/4423591.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!