初始化发生的情况
//: C13:Tree.h
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
#ifndef TREE_H
#define TREE_H
#include <iostream>
class Tree {
int height;
public:
Tree(int treeHeight) : height(treeHeight) {}
~Tree() { std::cout << "*"; }
friend std::ostream&
operator<<(std::ostream& os, const Tree* t) {
return os << "Tree height is: "
<< t->height << std::endl;
}
};
#endif // TREE_H ///:~
//: C13:NewAndDelete.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Simple demo of new & delete
#include "Tree.h"
using namespace std;
int main() {
Tree* t = new Tree(40);
cout << t;
delete t;
getchar();
} ///:~
通过打印Tree的值 得知构造函数被调用
这里通过调用参数为ostream和Tree*类型的重载operator<<来实现这个运算的
虽然这个函数被声明为一个友元,但它还是被定义为一个内联函数
定义一个友元函数为内联函数不会改变友元状态,而且它仍是全局函数而不是
一个类的成员函数
输出
Tree height is: 40
*