首页 > 代码库 > 2015年1月5日XX大学XX学院考试题

2015年1月5日XX大学XX学院考试题

六、程序题

   1.写一个复数类(操作符重载)

 

#include<iostream>
using namespace std;
class Complex{
public:
	Complex(double r=0.0,double i=0.0):read(r),imag(i){};
	Complex operator+(const Complex &c2)const;
	Complex operator-(const Complex &c2)const;
	void display()const;
private:
	double real,imag;

};
Complex Complex::operator+(const Complex &c2)const{
	return Complex(real=c2.real+real,imag=c2.imag+imag);
}
Complex Complex::operator-(const Complex &c2)const{
	return Complex(real=c2.real-real,imag=c2.imag-imag);
}
void Complex::display()const{
	cout<<"("<<real<<","<<imag<<")"<<endl;

}
void int main(){
	Complex c1(5,4),c2(2,10),c3;
	cout<<"c1="<<c1.display();
	cout<<"c2="<<c2.display();
	c3=c1-c2;
	cout<<"c3="<<c3.display();
}

2.写一个String类--转

#include<iostream>
using namespace std;
class String
{
	friend ostream& operator<<(ostream&,String&);
public:

	String(const char*str=NULL);//赋值兼构造函数
	String(const String &other)const;//赋值构造函数
	String& operator=(const String&other);//=
	String& operator+(const String&other);//+
	bool operator==(const String&other);//==
	char&operator[](unsigned int);//[]
	size_t size(){return strlen(m_data);}
	~String(void){
		delete[] m_data;
	};
private:
	char *m_data;
};
inline String::String(const char *str)
{
	if (!str)
		m_data=http://www.mamicode.com/0;"I love"
	String str2="www.oschina.net!";
	oschina str3=str1+str2;
	cout<<str3<<endl;
	cout<<str3.size()<<endl;
}

3.swap函数

#include<iostream>
using namespcae std;
int main(int argc, char const *argv[])
{
	int x=6,y=7;
	int *p=&x;
	int *q=&y;
	//错误写法
	void swap(int _x,int _y){
      temp=_y;
      _y=_x;
      _x=temp;

	}
	swap(x,y);
	//指针
	void swap(int *_p,int *_q){
		int *temp;
		temp=_p;
		_p=_q;
		_q=temp;
	}
	swap(*p,*q);

	return 0;
}     

4.冒泡函数

#include<iostream>
using namespace std;
void bubbleSort(int a[],int size);
int main()
{
   int array[]={34,65,12,43,67,5,78,10,3,70},k;
   int len=sizeof(array)/sizeof(int);
   cout<<"The orginal array are:"<<endl;
   for(k=0;k<len;k++)
      cout<<array[k]<<",";
   cout<<endl;
   bubbleSort(array,len);
   cout<<"The sorted array are:<<endl";
   for(k=0;k<len;k++)
      cout<<array[k]<<",";
   cout<<endl;
   system("pause");
   return 0;
}
void bubbleSort(int a[],int size)
{
     int temp;
     for(int pass=1;pass<size;pass++)
     {
        for(int k=0;k<size-pass;k++) 
           if(a[k]>a[k+1])
           {
                temp=a[k];
                a[k]=a[k+1];
                a[k+1]=temp;       
           }
        cout<<"第"<<pass<<"轮排序后:";
        for(int i=0;i<size;i++)
          cout<<a[i]<<",";
        cout<<endl;
     }
}

 

2015年1月5日XX大学XX学院考试题