码迷,mamicode.com
首页 > 其他好文 > 详细

实验三

时间:2018-04-08 21:18:23      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:实例   需要   nbsp   输入   程序   http   释放   add   构造函数   

在我的理解中类是实现一个目标的整体,在这个整体里有实现这个目标完整的函数,这样在实现目标时就只要调用类里面的函数就可以了。类需要定义和实现,也可以在定义的时候直接实现。

对象就是类的实现目标,可以用类的名字去定义一个对象,然后通过调用类里面的函数就可以实现对象要达成的目标。

构构造函数就相当于对某个函数进行赋初值,如果没有写构造函数,那么编译器会自动生成一个隐含的默认构造函数。

复制构造函数可以让函数被调用的时候把赋值这个操作再次实现。

析构函数是相当于清理函数(对象被删除前,需要做一个清理工作),例如:在函数运行结束时,会有内存残余,而这些残余内存要释放出来,析构函数可以释放它们。

下面是程序实例

4—11

#include<iostream>
using namespace std;
class square{
public:
square(float a,float b);
float area();
square(square &s);
~square(){}
private:
float length,width;
};
square::square(float a,float b){
length=a;
width=b;
}
square::square(square &s){
length=s.length;
width=s.width;
cout<<"Calling the copy constructor"<<endl;
}
float square::area(){
return length*width;
}
int main(){
float length,width;
cout<<"输入长和宽:";
cin>>length>>width;
square Area(length,width);
cout<<"矩形的面积是:"<<Area.area();
return 0;
}

 技术分享图片

 

 

4—20

#include<iostream>
using namespace std;
class Complex{
public:
Complex(double a,double b);
Complex(double a);
Complex(Complex &s);
void add(Complex &c);
void show();
~Complex(){}
private:
double real,imaginary;
};
Complex::Complex(double a,double b){
real=a;
imaginary=b;
}
Complex::Complex(double a){
real=a;
imaginary=0;
}
void Complex::add(Complex &c){
real=real+c.real;
imaginary=imaginary+c.imaginary;
}
void Complex::show(){
cout<<real<<"+"<<imaginary<<"i"; 
}
Complex::Complex(Complex &s){
real=s.real;
imaginary=s.imaginary;
cout<<"Calling the copy constructor"<<endl;
}
int main(){
Complex c1(3,5);
Complex c2(4.5);
c1.add(c2);
c1.show();
return 0;
}

技术分享图片

 

实验三

标签:实例   需要   nbsp   输入   程序   http   释放   add   构造函数   

原文地址:https://www.cnblogs.com/szb3115/p/8747236.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!