编写一个名为 boxVolume 的类,以长度、宽度和高度作为数据成员,以 readData()、dispData() 和computeVol() 作为函数。还编写一个 main() 函数来测试 boxVolume 类。
我试过了-
#include <iostream>
class BoxVolume
{
public:
float length;
float width;
float height;
void readData()
{
using namespace std
cout << "length: ";
cin >> 'BoxVolume::length';
cout << "width: ";
cin >> 'BoxVolume::width';
cout << "height: ";
cin >> 'BoxVolume::height';
}
void computeVolume()
{
float volume;
volume = 'void readData()::length' * 'void readData()::width' * 'void readData()::height';
}
void dispData()
{
using namespace std
cout << "Volume is:" << 'void computeVolume()::volume';
}
};
int main()
{
BoxVolume obj1,obj2,obj3;
obj1.readData();
obj2.computeVolume();
obj3.dispData();
};
您应该先阅读一本 C++ 入门书籍来了解该语言的基础知识,然后再开始编码。我建议Accelerated C++,因为它比它的竞争对手短,但仍然相当完整(在它发布时)。现在它缺乏对该语言中从 C++11 开始的后续标准的支持,因此目前 C++ Primer 可能是最好的选择,尽管它大约有 1000 页,并且新版本即将在几个月内推出。或者,还有 Stroustrup 的C++ 之旅。他是语言的创造者。
下面是代码的编译版本,我添加了封装,但如果您不关心公开数据成员,则可以使用
struct
代替 class
:
#include <iostream>
using namespace std;
class BoxVolume
{
public:
void readData()
{
cout << "length: ";
cin >> length;
cout << "width: ";
cin >> width;
cout << "height: ";
cin >> height;
}
float computeVolume()
{
return length * width * height;
}
void dispData()
{
//using namespace std // this is artistic I couldnt cancel it
cout << "Volume is: " << computeVolume() << endl;
}
private:
float length;
float width;
float height;
};
int main()
{
BoxVolume obj1,obj2,obj3;
obj1.readData();
obj2.computeVolume(); // data undefined for obj2
obj3.dispData(); // data undefined for obj3
};
是的,我忍不住回答这个问题。
#include<iostream>
using namespace std;
//create a class named 'volume'.
class volume{
public:
//create a constructor with the same name as class.
volume(double length,double breadth, double height ){
cout<<"Volume of the box is "<<length*breadth*height;
}
};
int main()
{
double length,breadth,height;
cout<<"The length of the box is : ";
cin>>length;
cout <<"the breadth of the box is : ";
cin>>breadth;
cout <<"the hieght of the box is : ";
cin>>height;
//assign the values in the constructor through keyboard.
volume(length,breadth,height);
}