如题,否则会在调用"std::cout<<this"时”偷偷“调用这个友元函数。本来是想看这个对象的指针值,却看到”不想看到的事情”。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
#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()
本文转自FrankNie0101 51CTO博客,原文链接http://blog.51cto.com/frankniefaquan/1936957:,如需转载请自行联系原作者