- 论坛徽章:
- 0
|
>>是不是可以认为所有函数返回值都可以改为引用???
不是,还存在着必须使用返回值的函数,比如你的complex类如果多一个operator+的话
比如这样形式来调用你的operator +:
complex a, b;
complex c = a + b;
那么你就得这么写你的class了.
- class complex
- {
- friend Complex operator +(Complex & temp1, Complex & temp2);
- }
- Complex operator +(Complex & temp1, Complex & temp2)
- {
- complex temp;
- temp.real =temp1.real + temp2.real;
- temp.imga =temp1.imga + temp2.imga;
- return temp;
- }
复制代码
这种时候返回引用显然是不合理的--因为temp在函数结束的时候就结束了自己的生命,这样就指向了一个无效的内存了.
这里只是简单的一说,更加详细的内容你可以看看
<<effictive c++>>(2nd version) 的Item 23: Don't try to return a reference when you must return an object. 中文翻译过来就是:在你必须返回一个对象的时候不要返回一个引用,里面详细的解释了上面的代码中为什么返回引用是不合理的.
对于返回值的效率,C++编译器提供了一种策略进行优化:named return value optimize,中文翻译就是命名对象返回优化....在<<深度探索C++物件模型>>中有讲述,简单的来说上面给出的operator+的函数进行说明,为了对这个函数调用进行优化,就得改为:
- Complex operator +(Complex & temp1, Complex & temp2)
- {
- return complex(temp1.real + temp2.real, temp1.imga + temp2.imga);
- /*
- temp.real =temp1.real + temp2.real;
- temp.imga =temp1.imga + temp2.imga;
- */
-
- }
复制代码
这里假设存在一个complex的构造函数complex(real, imga),这样写之后就把局部变量的构造和析构过程给优化掉了.
anyway,理解上面我说的东西都不是一时半会可以缓过来的.
>>上例中的" return *this ; " 中的this指针属于哪种变量???
这个问题就没有太多"技术含量"了,this指针的存在取决于它所依附的类是局部的全局的或者是static的.... |
|