在实例化类时,会自动调用构造函数
构造函数可以重构
当没有自定义构造函数时,系统会自动定义无参数的构造函数,但是一旦定义了一个构造函数,系统就不会自动定义无参数的构造函数
#include <iostream>
using namespace std;
class Box
{
public :
Box(int,int,int);
Box();
int volume( );
private :
int height;
int width;
int length;
};
//声明带参数的构造函数//声明计算体积的函数
Box::Box(int h,int w,int len) //在类外定义带参数的构造函数
{
height=h;
width=w;
length=len;
}
int Box::volume( ) //定义计算体积的函数
{
return (height*width*length);
}
int main( )
{
Box box3;
return 0;
}
报错:
unresolved external symbol "public: __thiscall Box::Box(void)" (??0Box@@QAE@XZ)
构造函数可以通过参数表的方式定义:
Box::Box(int h,int w,int len):height(h),width(w),length(len) //在类外定义带参数的构造函数
{
}
原文地址:http://www.cnblogs.com/jsy306/p/3789430.html