2014-09-12 68 views
-1

我正在学习有关课程,我在练习时偶然发现了这个问题。我很困惑,为什么我会得到amount的垃圾输出,并且为什么事先显示amount的正确值。正在显示的垃圾值

我哪里错了?

我粘贴了输出。

#include<iostream> 
using namespace std; 

class Resort{ 
    float charges ; 
    int days ; 
    float amount ; 
    float compute() ; 
public: 
    void getdata(); 
    void disp(); 
}; 

void Resort::getdata(){ 
    cout<<"\nCharges : "; 
    cin>>charges ; 
    cout<<"\nNo of days : "; 
    cin>>days ; 
} 

void Resort::disp(){ 
    cout<<"\nCharges : "<<charges 
     <<"\nDays : "<<days 
     <<"\nAmount : "<<compute()<<endl ; 
} 

float Resort::compute(){ 
    amount = (days*charges) ; 
    cout<<amount; 
} 

int main(){ 
    Resort obj ; 
    obj.getdata(); 
    cout<<"\n\n"; 
    obj.disp(); 
} 

enter image description here

+4

打开/关闭编译器的警告级别。 – chris 2014-09-12 12:46:47

+4

请编译所有警告和调试信息(例如'g +++ -Wall -g')并学习如何使用调试器** – 2014-09-12 12:47:32

+0

我启用了-Wall编译器设置。那是你在说@BasileStarynkevitch的那个人吗? – 2014-09-12 13:09:10

回答

0

不必返回从compute功能什么,但你在disp 输出其返回值。

你可能想是这样的:

​​
+0

它解决了这个问题,但为什么我的编译器没有显示错误?预先显示的值是什么?我正在使用代码块。 – 2014-09-12 12:52:16

+1

https://stackoverflow.com/questions/6260917/why-there-is-no-compiler-error-when-return-statement-is-not-present – dohashi 2014-09-12 12:56:39

0

为了防止变量垃圾值,您可以定义度假村类构造并提供默认值的变量,所以,即使您忘记处理变量的值,然后您将显示您初始化的值,而不是垃圾值。 例如 您可以在类定义中包含这样的构造函数。

public: 
    Resort() 
    { 
     charges = (float)0.0 ; 
     days = 0; 
     amount = (float)0.0; 
    } 

并专门针对上面的代码,你需要调用该函数用于打印值之前调用计算功能。

+0

为什么不只是0.0f? – acrilige 2014-09-12 13:33:54

0

disp您尝试打印返回值compute,但您忘记在那里添加返回值。您还可以打印两次,因为compute也打印到cout

未来的提示是始终尽可能多地打开编译器警告标志(对于g++,这是-Wall)。这样做可能会让你的编译器在compute中警告你省略了返回值。