// 構造函數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;
}
這裡是運行的結果: