#include <iostream>
#include <cmath>
using namespace std;
#define MAXLEN 100
class Complex{
double re;//实部
double im;//虚部
public:
Complex(double x=.0,double y=.0):re(x),im(y){}
void display() const;
//作为成员函数来重载运算符
Complex operator +(const Complex& z){
return Complex(re +z.re,im+z.im);
//重载为类的友元函数
}
};
void Complex::display() const
{
cout<<re;
if(fabs(im)<1e-9)
return;
cout<<"+"<<im<<"i";
}
int main ()
{
Complex z1(1.0,2.0);
Complex z2(3.0,4.0);
z1.display();
cout<<" ";
z2.display();
cout<<" ";
Complex z3;
z3=z1+z2;//z1.operator +(z2)
z3.display();
cout<<endl;return 0;
}
#include <iostream>
using namespace std;
class String
{
private:
char *s;
public:
String ();
String(int n);
String (const String& z);
String& operator=(const String& s);
friend String operator +(const String&s1,const String&s2);
friend bool operator <(const String&s1,const String&s2);
friend bool operator <=(const String&s1,const String&s2);
friend bool operator ==(const String&s1,const String&s2);
friend bool operator >(const String&s1,const String&s2);
friend bool operator >=(const String&s1,const String&s2);
friend bool operator !=(const String&s1,const String&s2);
}
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#include "mystring.h"
int main(){
String s1;
String s2(10);
String s3(s1);
}
String{
char *s;
public:
String ();
String(const char* str);
String (int n);
String (const String&s2);
friend
}
#include "mystring.h"
#include <cstring>
String::String()
{
s=new char[100];
s[0]='\0';
}
String::String(int n)
{
s=new char[100];
s[0]='\0';
}
String::String(const String& s2)
{
s=new char[strlen(s2.s)+1];
s[0]='\0';//表示是一个空的字符串
strcpy(s2.s);
}
String::~String()
{
if(s!=NULL)
delet s;
s=NULL;
}
ostream& operator<<(ostream& os,const String& str)
{
os<<str.os;
}
#include <iostream>
using namespace std;
class Complex
{public:
Complex() {real=0;imag=0;}
Complex(double r,double i) {real=r;imag=i;}
Complex complex_add(Complex &c2);
void display();
private:
double real;
double imag;
} ;
Complex Complex::complex_add(Complex &c2)
{Complex c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
void Complex::display()
{cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
int main(){
Complex c1(3,4),c2(5,-10),c3;
c3=c1.complex_add(c2);
cout<<"c1=";c1.display();
cout<<"c2=";c2.display();
cout<<"c1+c2=";c3.display();
return 0;
}
0143928--皮丽莉--c++作业
最新推荐文章于 2024-10-04 09:30:00 发布