构造函数用来在创建对象时初始化对象,为对象数据成员赋初始值。
类的数据成员是不能在类定义时初始化的,类定义并没有产生一个实体,而是给出了一个数据类型,不占用存储空间,无处容纳数据。
如果一个类所有的数据成员是公有的(public),则可以在定义对象时对数据成员进行初始化。
C++提供了构造函数(constructor)来处理对象的初始化问题。构造函数是类的一种特殊成员函数,不需要人为调用,而是在建立对象时自动被执行。
C++规定构造函数的名字与类的名字相同,并且不能指定返回类型。
#include
using namespace std;
class Cuboid{
public:
Cuboid(int l, int h, int d);
int volume()
{
return length * height * depth;
}
private:
int length, height, depth;
};
Cuboid::Cuboid(int l, int h, int d)
{
length = l;
height = h;
depth = d;
}
int main()
{
Cuboid a(1, 2, 3);
cout << "volume = " << a.volume() << endl;
Cuboid b(10, 20, 30);
cout << "volume = " << b.volume() << endl;
return 0;
}
(1)构造函数是在创建对象时自动执行的,而且只执行一次,并先于其他成员函数执行。构造函数不需要人为调用,也不能被人为调用。
(2)构造函数一般声明为公有的(public),因为创建对象通常是在类的外部进行的。
(3)一般不提倡在构造函数中加入与初始化无关的内容。
(4)每个构造函数应该为每个数据成员提供初始化。
与普通函数一样,构造函数具有函数名、形参列表和函数体。与其他函数不同的是,构造函数可以包含一个构造函数初始化列表:
#include
using namespace std;
class Cuboid{
public:
Cuboid(int l, int h, int d);
int volume(){
return length * height * depth;
}
private:
int length, height, depth;
};
Cuboid::Cuboid(int l, int h, int d) : length(l), height(h), depth(d)
{
cout << length << " " << height << " " << depth << endl;
}
int main()
{
Cuboid a(1, 2, 3);
cout << a.volume() << endl;
return 0;
}
#include
using namespace std;
class Point{
public:
Point(){
x = 0;
y = 0;
}
Point(int a, int b): x(a), y(b){
}
void display(){
cout << x << " " << y << endl;
}
private:
int x, y;
};
int main()
{
Point m;
m.display();
Point n(5, 20);
n.display();
return 0;
}
尽管一个类中可以包含多个构造函数,但对于每一个对象来说,建立对象时只执行其中一个,并非每个构造函数都被执行。
#include
using namespace std;
class Point{
public:
Point(int a=0, int b=0) : x(a), y(b){ }
void display(){
cout << x << " " << y << endl;
}
private:
int x, y;
};
int main()
{
Point k, m(1), n(1, 2);
k.display();
m.display();
n.display();
return 0;
}
(1)必须在类的内部指定构造函数的默认参数,不能在类外部指定默认参数。
(2)如果构造参数的全部参数都指定了默认值,则在定义对象时可以给一个或几个实参,也可以不给出实参。
(3)在一个类中定义了带默认参数的构造函数后,不能再定义与之有冲突的重载构造函数。
一般地,不应同时使用构造函数的重载和带默认参数的构造函数。