标签:style blog class code java tar
先看下以下代码
#include<iostream> using namespace std; int x = 1; int f1() { x = 2; return x; } int f2() { x = 3; return x; } int main() { //Test1 cout << x << ‘ ‘ << f1() << ‘ ‘ << f2() << endl; //2 2 3 //Test2 int i = 0; cout << i++ << ‘ ‘ << i << ‘ ‘ << ++i << endl; //1 2 2 //Test3 int s[] = {1, 2, 3}; int *p = s; //cout << *p << ‘ ‘ << *(p++) << ‘ ‘ << *(++p) << endl; //3 2 3 //cout << *p++ << ‘ ‘ << *++p << ‘ ‘ << *p << endl; //2 3 3 //cout << *p << ‘ ‘ << *++p << ‘ ‘ << *p << endl; //2 2 2 //cout << *++p << ‘ ‘ << *p << ‘ ‘ << *++p << endl; //3 3 3 //cout << *p++ << ‘ ‘ << *p << ‘ ‘ << *p++ << endl; //2 3 1 //cout << *p << " " << *p++ << " " << *p << endl;//2 1 2 }
ostream & operator <<(ostream &stream, T &t)
返回的是一个ostream类型的引用,为什么要返回引用,先留着待会说。
T operator ++() //++var { var = var+1; return var; } T operator ++(int dummy) //var++(dummy) { T tmp = var; var = var+1; return tmp; }
可以看到,++i比i++更有效率(少了一句T tmp=var;)
ostream & operator <<(ostream &stream, T &t)
要返回一个引用类型呢?如果不返回引用类型而是返回一个ostream对象的话,那么cout << a << b这样的式子就会有问题,编译不会通过的,因为cout<<a返回了一个ostream的对象,而这个对象是一个“值”,而不是一个“变量”,它不能作为左值。(比如a = 1是正确的,而1 = 1是错误的,因为1是一个值,而不是变量,不能作为左值)。
标签:style blog class code java tar
原文地址:http://www.cnblogs.com/chenyg32/p/3708164.html