首页 > 其他 > 详细

重载operator<<运算符时第二个参数最好不能写成指向对象的指针

时间:2017-06-15 16:05:47      阅读:312      评论:0      收藏:0      [点我收藏+]

如题,否则会在调用"std::cout<<this"时”偷偷“调用这个友元函数。本来是想看这个对象的指针值,却看到”不想看到的事情”。

#include <iostream>
using std::cout;
using std::endl;
using std::ostream;

class Tree {
  int height;
public:
  Tree(int treeHeight) : height(treeHeight) {
    cout << __func__ << "(), this = " << this << endl;
  }
  ~Tree() { cout << "~Tree()\n"; }
#if 1 
  friend ostream&
  operator<<(ostream& os, const Tree* t) {
    return os << "Tree height is: "
              << t->height << endl;
  }
#else
  friend ostream&
  operator<<(ostream& os, const Tree& t) {
    return os << "Tree height is: "
              << t.height << endl;
  }
#endif
}; 

int main() {
  Tree* t = new Tree(40);
  delete t;
  t = nullptr;
  delete t;
}

frank@userver:~/project/test/cpp/new_del$ g++ test2.cpp 

test2.cpp: In function ‘int main()’:

test2.cpp:31:7: error: ‘nullptr’ was not declared in this scope

   t = nullptr;

       ^

frank@userver:~/project/test/cpp/new_del$ g++ test2.cpp  -std=c++11

frank@userver:~/project/test/cpp/new_del$ ./a.out 

Tree(), this = Tree height is: 40


~Tree()


本文出自 “用C++写诗” 博客,谢绝转载!

重载operator<<运算符时第二个参数最好不能写成指向对象的指针

原文:http://frankniefaquan.blog.51cto.com/12613979/1936957

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