C++ 类构造函数 & 析构函数
C++ 类 & 对象
类的构造函数
类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时自动执行。
构造函数的名称与类的名称完全相同,且没有返回类型(连 void 也不能有)。构造函数通常用于为成员变量设置初始值。
若未显式定义构造函数,编译器会自动生成一个不执行任何操作的默认构造函数。
下面的实例有助于更好地理解构造函数的概念:
实例
#include <iostream>
using namespace std;
class Line
{
public:
Line();
void setLength(double len);
double getLength() const;
private:
double length;
};
Line::Line()
{
cout << "Object is being created" << endl;
length = 0.0;
}
void Line::setLength(double len)
{
length = len;
}
double Line::getLength() const
{
return length;
}
int main()
{
Line line;
line.setLength(6.0);
cout << "Length of line : " << line.getLength() << endl;
return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
Object is being created
Length of line : 6
带参数的构造函数
默认的构造函数没有任何参数,但如果需要,构造函数也可以带有参数。这样在创建对象时就会给对象赋初始值,无需再单独调用 set 函数,如下面的例子所示:
实例
#include <iostream>
using namespace std;
class Line
{
public:
Line(double len);
void setLength(double len);
double getLength() const;
private:
double length;
};
Line::Line(double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength(double len)
{
length = len;
}
double Line::getLength() const
{
return length;
}
int main()
{
Line line(10.0);
cout << "Length of line : " << line.getLength() << endl;
line.setLength(6.0);
cout << "Length of line : " << line.getLength() << endl;
return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
Object is being created, length = 10
Length of line : 10
Length of line : 6
使用初始化列表来初始化字段
C++ 推荐使用成员初始化列表来初始化成员变量。它的语法是在构造函数参数列表后加冒号(:),然后写 成员变量名(初始值)。
以下示例中,: length(len) 的含义是:用传入的参数 len 直接初始化成员变量 length。注意 cout 打印的是成员变量 length,而非参数 len,这样可以直观地验证成员变量已被正确赋值:
Line::Line(double len) : length(len)
{
cout << "Object is being created, length = " << length << endl;
}
上面的语法等同于如下在函数体内赋值的写法,两者输出结果完全相同:
Line::Line(double len)
{
length = len;
cout << "Object is being created, length = " << length << endl;
}
两种写法的区别在于:初始化列表在进入函数体之前就完成了成员变量的初始化,而函数体内赋值是先默认构造、再赋值,多了一步。对于 const 成员、引用成员以及没有默认构造函数的对象成员来说,初始化列表是唯一的初始化方式。
假设有一个类 C,具有多个字段 X、Y、Z 等需要进行初始化,只需在不同字段之间用逗号分隔,如下所示:
C::C(double a, double b, double c) : X(a), Y(b), Z(c)
{
}
注意:初始化列表中各成员的初始化顺序由它们在类中的声明顺序决定,而非书写顺序,建议保持一致以避免混淆。
类的析构函数
类的析构函数是类的一种特殊的成员函数,在对象的生命周期结束时(离开作用域或被 delete)自动执行,用于释放对象占用的资源(如动态内存、文件句柄等)。
析构函数的名称与类的名称完全相同,只是在前面加了个波浪号(~)作为前缀。它不会返回任何值,也不能带有任何参数,每个类只能有一个析构函数。
下面的实例有助于更好地理解析构函数的概念:
实例
#include <iostream>
using namespace std;
class Line
{
public:
Line();
~Line();
void setLength(double len);
double getLength() const;
private:
double length;
};
Line::Line()
{
cout << "Object is being created" << endl;
length = 0.0;
}
Line::~Line()
{
cout << "Object is being deleted" << endl;
}
void Line::setLength(double len)
{
length = len;
}
double Line::getLength() const
{
return length;
}
int main()
{
Line line;
line.setLength(6.0);
cout << "Length of line : " << line.getLength() << endl;
return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
Object is being created
Length of line : 6
Object is being deleted
C++ 类 & 对象
自娱、自乐
183***3822@qq.com
构造函数应用实例:
#include<iostream> #include<string> using namespace std; class Student { public: string name; string number; char X; int year; Student(string,string,char,int); //构造函数声明 void xianshi(void); //用于输出类成员的值 }; //成员函数定义,包括构造函数 Student::Student(string N,string n,char x,int y) //利用构造函数给类的成员赋值 { name = N; number = n; X = x; year = y; } void Student::xianshi() //输出成员的值 { cout<<name<<endl; cout<<number<<endl; cout<<X<<endl; cout<<year<<endl; } int main() //主函数 { cout<<"输入姓名:"; string N; cin>>N; cout<<"输入学号:"; string n; cin>>n; cout<<"输入性别(M 或 W):"; char x; cin>>x; cout<<"输入年龄:"; int y; cin>>y; Student S(N,n,x,y); //定义对象并对构造函数赋值 S.xianshi(); //引用输出函数 return 0; }自娱、自乐
183***3822@qq.com
eric
gxy***@163.com
参考地址
初始化列表的成员初始化顺序:
C++ 初始化类成员时,是按照声明的顺序初始化的,而不是按照出现在初始化列表中的顺序。
class CMyClass { CMyClass(int x, int y); int m_x; int m_y; }; CMyClass::CMyClass(int x, int y) : m_y(y), m_x(m_y) { };你可能以为上面的代码将会首先做 m_y=I,然后做 m_x=m_y,最后它们有相同的值。但是编译器先初始化 m_x,然后是 m_y,,因为它们是按这样的顺序声明的。结果是 m_x 将有一个不可预测的值。有两种方法避免它,一个是总是按照你希望它们被初始化的顺序声明成员,第二个是,如果你决定使用初始化列表,总是按照它们声明的顺序罗列这些成员。这将有助于消除混淆。
eric
gxy***@163.com
参考地址
突然的幸福
292***0456@qq.com
参考地址
初始化顺序最好要按照变量在类声明的顺序一致,否则会出现下面的特殊情况:
#include<iostream> using namespace std; class Student1 { public: int a; int b; void fprint(){ cout<<" a = "<<a<<" "<<"b = "<<b<<endl; } Student1(int i):b(i),a(b){ } //异常顺序:发现a的值为0 b的值为2 说明初始化仅仅对b有效果,对a没有起到初始化作用 // Student1(int i):a(i),b(a){ } //正常顺序:发现a = b = 2 说明两个变量都是初始化了的 Student1() // 无参构造函数 { cout << "默认构造函数Student1" << endl ; } Student1(const Student1& t1) // 拷贝构造函数 { cout << "拷贝构造函数Student1" << endl ; this->a = t1.a ; } Student1& operator = (const Student1& t1) // 赋值运算符 { cout << "赋值函数Student1" << endl ; this->a = t1.a ; return *this; } }; class Student2 { public: Student1 test ; Student2(Student1 &t1){ test = t1 ; } // Student2(Student1 &t1):test(t1){} }; int main() { Student1 A(2); //进入默认构造函数 Student2 B(A); //进入拷贝构造函数 A.fprint(); //输出前面初始化的结果 }两种不同的初始化方法结果如下:
异常初始化顺序:
正常初始化顺序:
由上面的例子可知,初始化列表的顺序要跟你在类声明的顺序要一致。否则像上面的那种特殊情况,有些变量就不会被初始化。经过测试发现,类中变量为下面的情况也是能够正常初始化的:也就是说,只要成员变量的初始化不依赖其他成员变量,即使顺序不同也能正确的初始化。
int a; int b; int c; Student1(int i):b(i),a(i),c(i){} main: Student1 A(2); A.fprint();结果:
int a; int b; int c; Student1(int i,int j,int k):b(i),a(j),c(k){} main: Student1 A(2,3,4); A.fprint();突然的幸福
292***0456@qq.com
参考地址
冰封绝杀
mz9***99999@163.com
改进了下上面的列子:
#include<iostream> using namespace std; class Student1 { public: int a=0; int b=0; void fprint() { cout << " a = " << a << " " << "b = " << b << "\n"<<endl; } Student1() { cout << "无参构造函数Student1" << endl; } Student1(int i):a(i),b(a) { cout << "有参参构造函数Student1" << endl; } Student1(const Student1& t1) { cout << "拷贝构造函数Student1" << endl; this->a = t1.a; this->b = t1.b; } Student1& operator = (const Student1& t1) // 重载赋值运算符 { cout << "赋值函数Student1" << endl; this->a = t1.a; this->b = t1.b; return *this; } }; class Student2 { public: Student1 test; Student2(Student1& t1) { t1.fprint(); cout << "D: "; test = t1; } // Student2(Student1 &t1):test(t1){} }; int main() { cout << "A: "; Student1 A; A.fprint(); cout << "B: "; Student1 B(2); B.fprint(); cout << "C: "; Student1 C(B); C.fprint(); cout << "D: "; Student2 D(C); D.test.fprint(); }冰封绝杀
mz9***99999@163.com
Jason C
792***803@qq.com
一个类内可以有多个构造函数,可以是一般类型的,也可以是带参数的,相当于重载构造函数,但是析构函数只能有一个。
class Matrix { public: Matrix(int row, int col); //普通构造函数 Matrix(const Matrix& matrix); //拷贝构造函数 Matrix(); //构造空矩阵的构造函数 void print(void); ~Matrix(); };Jason C
792***803@qq.com
yushuoqi
541***814@qq.com
参考地址
这里增加一个对构造函数次数的题目来加深对构造函数的理解。
题目:假定AB为一个类,则执行 ”AB a(2), b[3], *p[4];“ 语句时调用该类构造函数的次数为4次。
解析:
AB a(2) 为调用一次构造函数;
AB b[3] 代表b是AB类的对象数组,包含3个对象,因此为调用3次构造函数;
AB *p[4] 代表p是AB类的对象指针数组,包含4个类对象指针,不调用构造函数。
补充思路:
1. AB *a = new AB; 代表调用默认构造函数:
2. AB b(*a); 代表用括号中的内容*a来初始化Test类型的对象b,调用拷贝构造函数;
3. AB c; 代表定义一个AB类型的对象c,并且没有赋初值,调用默认构造函数;
4. c = a; 代表用a对象给c对象赋值,这里的赋值运算符实际上是调用了赋值构造函数。
5. AB d = a; 代表进行变量d的定义和初始化操作,虽然有赋值运算符=在,但是其实质还是初始化,并不属于赋值的范畴,因此这里调用的是复制构造函数,而非赋值构造函数。
yushuoqi
541***814@qq.com
参考地址