构造函数的创建
// 构造函数2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
class Box
{
public:
Box();
Box(int, int, int); //声明带参数的构造函数
int volume(); //声明计算体积的函数
private:
int height;
int width;
int length;
};
Box::Box()
{
height = 10;
width = 10;
length = 10;
}
Box::Box(int h, int w, int len) //在类外定义带参数的构造函数
{
height = h;
width = w;
length = len;
}
int Box::volume() //定义计算体积的函数
{
return(height*width*length);
}
int main()
{
Box box;
cout << "The volume of box1 is " << box.volume() << endl;
Box box1(12, 25, 30); //建立对象 box1,并指定 box1 长、宽、高的值
cout << "The volume of box1 is " << box1.volume() << endl;
Box box2(12, 35, 24); //建立对象 box2,并指定 box2 长、宽、高的值
cout << "The volume of box2 is " << box2.volume() << endl;
Box box3(123, 234, 256);
cout << "The volume of box3 is " << box3.volume() << endl;
system("pause");
return 0;
}
这里是运行的结果: