|
|
5鱼币
在学到重载流插入运算符<<
- #include<iostream>
- #include<stdlib.h>
- using namespace std;
- class Complex
- {
- public:
- Complex( double r = 0, double i = 0) : real(r), imag(i){} //构造函数初始化
- Complex operator + ( Complex &c2 ); //复数相加函数声明
- friend ostream & operator << ( ostream&, Complex&); // 运算符重载 ,我说的就是这一句
- private:
- double real;
- double imag;
- };
- Complex Complex::operator + ( Complex &c2 )
- {
- return Complex( real + c2.real , imag + c2.imag );
- }
- ostream & operator << ( ostream &output, Complex &c ) //还有这一句,把第一个&去掉的话
- {
- output << "(" << c.real << "+" << c.imag << "i)" << endl;
- return output;
- }
- int main()
- {
- Complex c1( 1, 3), c2( 4, 7 ), c3;
- c3 = c1 + c2;
- cout << c3;
- system( "pause");
- return 0;
- }
复制代码 这个程序是对的
我的想法是 既然 cout 是 ostream 类的对象,那为什么不能把 ostream & operator << ( ostream &output, Complex &c )
这一句 ostream & operator << 的 & 给去掉,我觉得把 & 去掉的话返回output 正好是ostream类型,不是正好吗?
为什么去掉 & 会出错呢
|
最佳答案
查看完整内容
出于某种原因,ostream和istream类型的对象都能不能被复制。去掉&的话在函数参数值传递过程中将复制ostream对象,从而导致错误。
关于ostream和istream类型的对象都能不能被复制,主要是为了它们设计的简单而规定的。
|