命名空间里的运算符

考虑二元运算符@,如果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

转载于:https://www.cnblogs.com/wuhanqing/p/4423591.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值