您的位置:首页 > 编程语言 > C语言/C++

【C++学习】构造函数、拷贝构造函数、析构函数小结

2015-05-05 10:08 537 查看
一、构造函数

1.构造函数没有返回值,不能有return语句,不能为其定义返回类型,包括void类型在内。

2.构造函数是类的成员函数,具有一般成员函数的所有性质——可访问类的所有成员,可以是内联函数,可带形参,可带默认的形参值,可重载。

3.不能在类定义时给成员变量赋初值,通常使用构造函数来进行。

4.构造函数的主要功能是为对象分配存储空间。若在类中没有定义构造函数,则会生成默认构造函数,这个函数只能给对象开辟存储空间,不能对数据成员赋初值。

下面是构造函数使用实例:

/*构造函数——(1)构造函数重载*/
#include <iostream>
using namespace std;

class Point
{
private:
double x, y;
//int z = 6; //不能在类定义时给成员变量赋值
public:
Point();//声明不带参数的构造函数
Point(double fx, double fy);//重载构造函数
void print();
};

Point::Point()
{
x = 0.0;
y = 0.0;
}

Point::Point(double fx, double fy)
{
x = fx;
y = fy;
}

void Point::print()
{
cout << x << "\t" << y <<endl;
}

void main()
{
Point p1;
Point p2(3,5);
cout << "the x and y of p1:" << "\t";
p1.print();
cout << "the x and y of p2:" << "\t";
p2.print();
system("pause");
}

运行结果如下:



上述程序中,若在类定义中去掉Int z=0的注释;并将 print() 函数定义改成:cout << x << "\t" << y <<"\t"<<z<< endl;  则出现如下结果:



这与书中的结论——“不能在类定义时给成员变量赋初值”相悖,也许是编译器的问题或是其他的原因,这点留待以后探究。

/*构造函数——(2)声明带默认参数的构造函数*/
#include <iostream>
using namespace std;

class Point
{
private:
double x, y;
public:
Point(double fx = 0.0, double fy = 1.1);//声明带默认参数的构造函数
//Point();//声明了上一行时,若再声明这个构造函数,则编译 Point p1;会出错,显示"类Point包含多个默认构造函数,对重载函数的调用不明确"
void print();
};

Point::Point(double fx, double fy)
{
x = fx;
y = fy;
}

void Point::print()
{
cout << x << "\t" << y << endl;
}

void main()
{
Point p1;
Point p2(3);
Point p3(5, 6);
cout << "the x and y of p1:" << "\t";
p1.print();
cout << "the x and y of p2:" << "\t";
p2.print();
cout << "the x and y of p3:" << "\t";
p3.print();
system("pause");
}运行结果如下:



二、拷贝构造函数

拷贝构造函数在一下三种情况下会被调用:

1.用类的一个对象去初始化该类的另一个对象。

2.类的对象作为函数的形参。

3.类的对象作为函数的返回值。

下面是拷贝构造函数使用实例:

/*拷贝构造函数——拷贝构造函数被调用的三种情况*/
#include <iostream>
using namespace std;

class Point
{
private:
int x, y;
public:
Point(int m = 2, int n = 3); //定义构造函数(带默认参数的)
Point(Point &p); //声明拷贝构造函数
int getx();
int gety();
};

Point::Point(int m, int n)
{
x = m;
y = n;
}

Point::Point(Point &p) //定义拷贝构造函数
{
static int i = 1;
x = p.x + 10;
y = p.y + 20;
cout << "第" << i++ << "次调用拷贝构造函数后:"<<"\t" ;
}

int Point::getx()
{
return x;
}

int Point::gety()
{
return y;
}

void f(Point p) //对象作形参
{
cout << p.getx() << "\t" << p.gety() << endl;
}

Point g() //对象作返回值
{
Point p(5, 6);
return p;
}

void main()
{
Point p1; //调用构造函数创建对象p1
cout << p1.getx() << "\t" << p1.gety() << endl;
Point p2(p1); //调用拷贝构造函数的第一种情况
cout << p2.getx() << "\t" << p2.gety() << endl;
f(p2); //调用拷贝构造函数的第二种情况——对象作形参
Point p3 = g(); //调用拷贝构造函数的第三种情况——对象作返回值
cout << p3.getx() << "\t" << p3.gety() << endl;
system("pause");
}


运行结果如下:



三、析构函数

1.一个类中只能有一个析构函数,析构函数无参数、无返回值、不能重载。

2.若没有显式定义,系统会生成默认析构函数,其是一个空函数。对于大多数类,默认析构函数能满足要求,但若需要进行其他处理,需显式定义。



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐