答案-c++面向对象程序设计课后习题答案(谭浩强版) 下载本文

c3=c1+c2;

cout<<\ c3.display(); c3=c1-c2;

cout<<\ c3.display(); c3=c1*c2;

cout<<\ c3.display(); c3=c1/c2;

cout<<\/c2=\ c3.display(); return 0; } 3:

#include //用VC++时改为∶ #include using namespace std; //用VC++时为取消此行 class Complex {public:

Complex(){real=0;imag=0;}

Complex(double r,double i){real=r;imag=i;} Complex operator+(Complex &c2); Complex operator+(int &i);

friend Complex operator+(int&,Complex &); void display(); private:

double real; double imag; };

Complex Complex::operator+(Complex &c) {return Complex(real+c.real,imag+c.imag);}

Complex Complex::operator+(int &i) {return Complex(real+i,imag);}

void Complex::display()

{cout<<\

Complex operator+(int &i,Complex &c) {return Complex(i+c.real,c.imag);}

int main()

{Complex c1(3,4),c2(5,-10),c3;

int i=5; c3=c1+c2;

cout<<\ c3.display(); c3=i+c1;

cout<<\ c3.display(); c3=c1+i;

cout<<\ c3.display(); return 0; } 4:

#include using namespace std;

class Matrix {public:

Matrix(); friend Matrix operator+(Matrix &,Matrix &); void input(); void display(); private:

int mat[2][3]; };

Matrix::Matrix() {for(int i=0;i<2;i++) for(int j=0;j<3;j++) mat[i][j]=0; }

Matrix operator+(Matrix &a,Matrix &b) {Matrix c;

for(int i=0;i<2;i++) for(int j=0;j<3;j++)

{c.mat[i][j]=a.mat[i][j]+b.mat[i][j];} return c; }

void Matrix::input() {cout<<\ for(int i=0;i<2;i++) for(int j=0;j<3;j++) cin>>mat[i][j]; }

//定义Matrix类 //默认构造函数 //重载运算符“+” //输入数据函数 //输出数据函数 //定义构造函数 //定义重载运算符“+”函数 //定义输入数据函数

void Matrix::display() //定义输出数据函数 {for (int i=0;i<2;i++) {for(int j=0;j<3;j++)

{cout<

int main() {Matrix a,b,c; a.input(); b.input();

cout<

cout<

c=a+b; 加

cout<

#include //using namespace std; class Matrix {public: Matrix();

friend Matrix operator+(Matrix &,Matrix &);

friend ostream& operator<<(ostream&,Matrix&); friend istream& operator>>(istream&,Matrix&); private:

int mat[2][3]; };

Matrix::Matrix() {for(int i=0;i<2;i++) for(int j=0;j<3;j++) mat[i][j]=0; }

Matrix operator+(Matrix &a,Matrix &b) {Matrix c;

for(int i=0;i<2;i++)

//用重载运算符“+”实现两个矩阵相 for(int j=0;j<3;j++)

{c.mat[i][j]=a.mat[i][j]+b.mat[i][j]; } return c; }

istream& operator>>(istream &in,Matrix &m) {cout<<\ for(int i=0;i<2;i++) for(int j=0;j<3;j++) in>>m.mat[i][j]; return in; }

ostream& operator<<(ostream &out,Matrix &m) {for (int i=0;i<2;i++) {for(int j=0;j<3;j++)

{out<

int main() { Matrix a,b,c; cin>>a; cin>>b;

cout<

cout<

#include using namespace std; class Complex {public:

Complex(){real=0;imag=0;}

Complex(double r){real=r;imag=0;}

Complex(double r,double i){real=r;imag=i;} operator double(){return real;} void display(); private:

double real;