使用对象数组求长方体体积
#include
using namespace std;
/* 求三个长方体的体积
成员函数:
(1)计算体积
(2)输出三个长方体的体积
数据成员:
长(length)宽(width)高(height)
*/
//定义类
class Box{
public:
//带默认参数的构造函数
Box(float l=10,float w=10,float h=10):length(l),width(w),height(h){}
//功能:计算、输出
float vol_();
void show();
//重载 << 操作符
friend ostream & operator<<(ostream &out,Box &b);
private:
float length;
float width;
float height;
float vol;
};
//计算函数的实现
float Box::vol_(){
vol=length*width*height;
return vol;
}
//输出函数的实现
void Box::show(){
cout<//重载函数的实现
ostream & operator<<(ostream &out,Box & b){
out<return out;
}
int main()
{
Box box1;
Box box2(15,18,20);
Box box3(16,20,26);
cout<3]={box1,box2,box3};
for(int i=0;i<3;i++){
cout<system("pause");
return 0;
}
原本是一个简单的对象数组的使用,但是我自行加入了运算符重载,于是就涉及到地址与值输出的相关知识。结果显示的是地址不是值,对于对象数组,不知道应该怎么修改代码得以实现输出值的目的,希望可以得到能人指点一二(根源是基础知识不扎实,最好可以说说原理),谢谢!
显示的不是地址,而是vol的值,只是你这里没有初始化vol。
而且这里你实现了vol_()函数,class中就没有必要有vol成员了,因为本来vol就是体积,不是你类的属性,你的类属性就只有长宽高,只是你可以提供计算体积的方法。
另外,你重载了输出运算符,就不用show方法了吧。
仅供参考:
#include<iostream>
using namespace std;
/* 求三个长方体的体积
成员函数:
(1)计算体积
(2)输出三个长方体的体积
数据成员:
长(length)宽(width)高(height)
*/
//定义类
class Box {
public:
//带默认参数的构造函数
Box(float l = 10, float w = 10, float h = 10) :length(l), width(w), height(h) { }
//功能:计算、输出
float vol_();
//void show();
//重载 << 操作符
friend ostream & operator<<(ostream &out, Box &b);
private:
float length;
float width;
float height;
};
//计算函数的实现
float Box::vol_() {
return length * width*height;
}
//输出函数的实现 可去掉
/*
void Box::show() {
cout << vol_() << endl;
}*/
//重载函数的实现
ostream & operator<<(ostream &out, Box & b) {
out << b.vol_();
return out;
}
int main()
{
Box box1;
Box box2(15, 18, 20);
Box box3(16, 20, 26);
cout << box1 <<endl;
Box a[3] = { box1,box2,box3 };
for (int i = 0; i < 3; i++) {
cout << a[i] << endl;
}
system("pause");
return 0;
}