LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 777|回复: 5

"->"运算符应该怎么重载?

[复制链接]
发表于 2003-8-10 15:36:58 | 显示全部楼层 |阅读模式
看到auto_ptr里面的声明是这样的:
X* operator->() const;
Returns the underlying pointer.

有点不能理解,有这样一段代码

  1. //
  2.    // auto_ptr.cpp
  3.    //
  4.    #include <iostream.h>
  5.    #include <memory>

  6.    //
  7.    // A simple structure.
  8.    //
  9.    struct X
  10.    {
  11.        X (int i = 0) : m_i(i) { }
  12.        int get() const { return m_i; }
  13.        int m_i;
  14.    };

  15.    int main ()
  16.    {
  17.       //
  18.       // b will hold a pointer to an X.
  19.       //
  20.       auto_ptr<X> b(new X(12345));
  21.       //
  22.       // a will now be the owner of the underlying pointer.
  23.       //
  24.       auto_ptr<X> a = b;
  25.       //
  26.       // Output the value contained by the underlying pointer.
  27.       //
  28.       cout << a->get() << endl;
  29.       //
  30.       // The pointer will be deleted when a is destroyed on
  31.       // leaving scope.
  32.       //
  33.       return 0;
  34.    }

复制代码


在这里按照声明"a->"应该是返回一个X*,那么它怎么能直接就跟get()呢,而不能使用->get()?
发表于 2003-8-10 17:36:42 | 显示全部楼层
如果你把a->get()换成(a.operator->())->get(),照样能编译通过。可见,a本身并没有get()这样的成员函数,是编译器自动地为->返回的X*调用那些函数。
 楼主| 发表于 2003-8-10 18:57:00 | 显示全部楼层
但是我如果写成(a->)->get()却无法通过,这个跟(a.operator->())->get()
应该是一样的呀。
发表于 2003-8-10 20:09:55 | 显示全部楼层
那里有这样的语法,你见过有(a->)这样使用->的吗?运算符重载是为了让代码更易写易读,不是产生一种新的语法形式。
 楼主| 发表于 2003-8-10 23:48:47 | 显示全部楼层
这个我知道,但是运算符重载的时候,a->不就相当于是a.operator->()吗?
发表于 2003-8-11 07:42:41 | 显示全部楼层
但是在使用的形式上仍然要按照指针的形式来使用。当a->get()时,编译时知道把a->转换成a.operator->()再根据返回值来调用get()。如果只是a->,这种形式是没有意义的,编译器找不到->所指向的对象,只能 认为是语法错误。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表