类的四种基本默认函数:构造函数、析构函数、拷贝构造函数、赋值函数。
构造函数:创建类时,系统自动调用构造函数,用以初始化,分配空间,没有自定义的构造函数时,系统默认一个无参数的构造函数。
class book
{
private:
int isBook;
string BookName;
public:
book() //构造函数
{
cout<<"Construct!"<<endl;
}
book(int ib,string bn):isBook(ib),BookName(bn) //构造函数
{
cout<<"Construct with "<<ib<<" "<<bn<<endl;
};
}
析构函数:当对象超出其定义范围时(即释放该对象时),编译器自动调用析构函数。
如果一个对象被定义在一个函数体内,则当这个函数结束时,该对象的析构函数被自动调用。
若一个对象是使用new运算符动态创建的,在使用delete运算符释放它时,delete将会自动调用析构函数。用new创建的对象,必须用delete销毁。
~book() //析构函数
{
cout<<"Destruct!"<<endl;
}
拷贝构造函数:
book a(1,"History");
book b=a;
当此类调用时系统会调用拷贝构造函数。
如果不自定义拷贝构造函数,系统会自动将变量拷贝给新的类。
book(const book &a) //拷贝函数
{
cout<<"Copy!"<<endl;
this->isBook=a.isBook;
this->BookName=a.BookName;
}
赋值函数:原类已被构建,用另一个类给其赋值时系统调用。与拷贝函数的区别在于,调用赋值函数说明原类已有值:
book a(1,"History");
book b;
b=a;
book& operator =(const book& a) //赋值函数
{
cout<<"Assign with "<<a.isBook<<" "<<a.BookName<<endl;
this->BookName=a.BookName;
this->isBook=a.isBook;
return *this;
}
全部代码测试:
//
// main.cpp
// ClassStudy
//
// Created by 王一帆 on 2018/9/30.
// Copyright © 2018 王一帆. All rights reserved.
//
#include <iostream>
#include <string>
using namespace std;
class book
{
private:
int isBook;
string BookName;
public:
book() //构造函数
{
cout<<"Construct!"<<endl;
}
book(int ib,string bn):isBook(ib),BookName(bn) //构造函数
{
cout<<"Construct with "<<ib<<" "<<bn<<endl;
};
~book() //析构函数
{
cout<<"Destruct!"<<endl;
}
book(const book &a) //拷贝函数
{
cout<<"Copy!"<<endl;
this->isBook=a.isBook;
this->BookName=a.BookName;
}
book& operator =(const book& a) //赋值函数
{
cout<<"Assign with "<<a.isBook<<" "<<a.BookName<<endl;
this->BookName=a.BookName;
this->isBook=a.isBook;
return *this;
}
int getIsBook()
{
return isBook;
}
string getBookName()
{
return BookName;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
book a(1,"History");
book b=book(a);
book c;
c=a;
cout<<b.getIsBook()<<" "<<b.getBookName()<<endl;
return 0;
}
输出结果为:
Construct with 1 History a的构造函数的调用
Copy! a的拷贝构造函数(将a拷贝给b)
Construct! c的构造函数
Assign with 1 History c的赋值函数
1 History 输出b的信息
Destruct! 函数终止时,按c,b,a的顺序依次调用其析构函数
Destruct!
Destruct!
Program ended with exit code: 0