| 网站首页 | 业界新闻 | 群组 | 交易 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
 跟大牛学C++学算法数据结构

已结贴   问题点数：20  回复次数：1

#include "stdafx.h"
#include<iostream>
using namespace std;

class complex {
public:
complex() { real = 0, image = 0; }
complex(double r, double i) { real = r; image = i; }
friend complex add(complex &c1, complex  &c2);
void display();
private:
double real;
double image;
};
complex add(complex &c1, complex  &c2) {
complex c3;
c3.real = c1.real + c2.real;
c3.image = c1.image + c2.image;
return c3;
}
void complex::display() {
cout << real << "+" << image << "i" << endl;
}
int main() {
complex c1(3, 4), c2(6, 8), c3;
cout << "c1=", c1.display();
cout << "c2=", c2.display();
cout << "c3=", c3.display();
return 0;
}
得分:20

#include <iostream>

class complex
{
public:
complex( double real=0, double imag=0 ) : real_(real), imag_(imag)
{
}
private:
double real_, imag_;

friend complex operator+( const complex& a, const complex& b );
friend std::ostream& operator<<( std::ostream& os, const complex& cpl );
};

complex operator+( const complex& a, const complex& b )
{
return complex( a.real_+b.real_, a.imag_+b.imag_ );
}

std::ostream& operator<<( std::ostream& os, const complex& cpl )
{
return os << cpl.real_ << '+' << cpl.imag_ << 'i';
}

using namespace std;

int main( void )
{
complex c1(3, 4), c2(6, 8);
complex c3 = c1 + c2;
cout << "c1 = " << c1 << '\n'
<< "c2 = " << c2 << '\n'
<< "c3 = " << c3 << endl;
}

• 2
• 1/1页
• 1