谭老师的那本CC+,错了,是C++,上到带参数的构造函数时,又一道例题是这样的:
#include <iostream>
using namespace std;
class Box
{
float length,height,width;
public:
float volume();
Box(float,float,float);
};
float Box:: volume()
{
return length*height*width;
}
Box:: Box(float l,float h,float w)
{
length=l;
height=h;
width=w;
}
int main(int argc, char *argv[])
{
Box count1(1.1,1.2,1.3);
Box count2(2.1,2.2,2.3);
cout <<count1.volume()<<endl;
cout <<count2.volume()<<endl;
}
我觉得多此一举,如果对对象中的数据成员进行赋值的话也可以不用这种方法,可以把源代码改成这样不就得了?:
#include <iostream>
using namespace std;
class Box
{
float length,height,width;
public:
float volume(float,float,float);
}one,two;
float Box:: volume(float l,float h,float w)
{
return l*h*w;
}
int main(int argc, char *argv[])
{
cout <<one.volume(1.1,1.2,1.3)<<endl;
cout <<two.volume(2.1,2.2,2.3)<<endl;
}
这样的话,就不用多写一个构造函数了?