注册 登录
编程论坛 C++教室

体积输出问题

呜呜1 发布于 2013-10-20 11:06, 576 次点击
#include<iostream>
using namespace  std;
class  Box
{  public:
  Box(int,int,int);
  int volume();
  void  display();
private:
    int height;
    int width;
    int length;
};
Box::Box(int h,int w,int len):height(h),width(w),length(len){}

int Box::volume()
{return (height*width*length);}
void  Box::display()
{cout<<volume()<<endl;}
int main()
{ Box box1(15,20,30);
cout<<box1.volume<<endl;
cout<<box1.display<<endl;
return  0;
}
,长,宽,高我分别赋值15,20,30,为什么程序的输出结果是1呢??
8 回复
#2
blueskiner2013-10-20 11:10
函数调用要加括号的
cout<<box1.volume()<<endl;
cout<<box1.display()<<endl;
#3
呜呜12013-10-20 13:23
回复 2楼 blueskiner
我在vc++里面运行的程序,加了()之后就报错,你试了吗
#4
blueskiner2013-10-20 15:16
#include <iostream>

class Box
{
public:
    Box(int h, int w, int len);
    int volume();
    void display();
private:
    int height;
    int width;
    int length;
};
Box::Box(int h, int w, int len) : height(h), width(w), length(len)
{
}

int Box::volume()
{
    int tmp = height * width;
    return (tmp * length);
}
void Box::display()
{
    std::cout<<volume()<<std::endl;
}

int main(int argc, char** argv)
{
    Box box1(15, 20, 30);
    std::cout<<box1.volume()<<std::endl;
    box1.display();
    return 0;
}
#5
苑天尤2013-10-20 17:00
你看这个程序符合你的要求不?
#include<iostream>
 using namespace  std;
 class  Box
 {
 public:
   Box(int,int,int);
   int volume();
   void  display();
 private:
     int height;
     int width;
     int length;
 };
 Box::Box(int h,int w,int len):height(h),width(w),length(len){}
 
int Box::volume()
 {
    return (height*width*length);
}
 void  Box::display()
 {
     cout<<volume()<<endl;
 }
 int main()
 {
     Box box1(15,20,30);
 cout<<box1.volume()<<endl;
 box1.display ();
 return  0;
 }
#6
呜呜12013-10-20 21:37
回复 5楼 苑天尤
可以的,为什么我的程序就运行不出来呢,
#7
RockSonE2013-10-21 09:43
void  Box::display()
{cout<<volume()<<endl;}

cout<<box1.display<<endl;

看看这里,Box::display()函数是void型的吧?里面的内容本来就是输出了体积cout<<volume()<<endl;但又在主函数里面cout<<box1.display<<endl;,这就不行了吧?这样只会输出判断值,真为1,假为0.
#8
IT男year2013-10-21 12:09
回复 7楼 RockSonE
对咯!大神就是大神!
#9
呜呜12013-10-21 12:44
回复 7楼 RockSonE
非常感谢
1