#include<iostream>
#ifndef STRNGBAD H
#define STRNGBAD H
class StringBad
{
private:
char *str;
int len;
static int num_strings;
public:
StringBad(char *str); //constructor
StringBad(); //default constructor
~StringBad();
friend std::ostream & operator <<(std::ostream & os , const StringBad & st);
};
#endif
求大神解释一下这一句:
friend std::ostream & operator <<(std::ostream & os , const StringBad & st);
那个&运算符是什么意思?以及括号中的参量?
在C++里面,&可以表示对变量的引用,作用有点像指针。比如:
int iVal;
int* pIVal=&iVal; //pIVal指向iVal
int& iVal2=iVal; //iVal2等同于 iVal
iVal=123;
printf("*pIVal=%d, iVal2=%d", *pIVal, iVal2); //输出结果: *pIVal=123, iVal2=123
friend std::ostream & operator <<(std::ostream & os , const StringBad & st);
这句话里的三个&全部都表示引用。
引用的优点:主要是在对对象、容器对象引用时才会体现他的优越性。比如传递参数为一个容器内对象引用,就不必再像按值传递那样,复制一个传递的对象,直接对该对象进行操作,同时也可以减少开销。
下面来说说重载的<<为什么要返回引用,我说你仔细想一下就明白了,你的函数会修改你操作的流,而流是全局的,不是临时变量,是系统托管的。如果不返回引用,后面对流的操作就是无效的了,因为你返回的只是某时流的一个拷备,以后对它的操作不会显示出来了。
貌似这里是运算符重载…