C ++意外的数字输出

时间:2013-11-10 00:13:26

标签: c++ class output

编辑:通过以下建议解决了问题。将evaluate()的返回类型从int更改为void。

我正在学习如何使用课程,而且我遇到了一个问题。我不断得到一个输出:

0
They are not equal.
4469696

最后一个号码来自哪里?它应该在之后的某个地方 这条线

std::cout << Thing.evaluation(Thing.getValue()) << std::endl;

但我没有看到任何可能输出该值的内容。是内存泄漏吗?

#include <iostream>
#include <conio.h>

class classTest
{
      public:
             int equivalency(int x, int y)
             {
                 if (x == y)
                 {
                       value = 1;
                 } else
                 {
                       value = 0;      
                 }
             }

             int evaluation(int z)
             {
                 if (z == 0)
                 {
                       std::cout << "They are not equal." << std::endl;
                 } else 
                  {
                        std::cout << "They are equal." << std::endl;
                  }
             }

             int getValue()
             {
                 return value;
             }

       private:
              int value;
};

int main()
{
    int a = 0, b = 0;
    classTest Thing;

    std::cout << "Enter two numbers for comparison." << std::endl;
    std::cin >> a >> b;

    Thing.equivalency(a, b);

    std::cout << Thing.getValue() << std::endl;

    std::cout << Thing.evaluation(Thing.getValue()) << std::endl;

    getch();
    return 0;
}

1 个答案:

答案 0 :(得分:8)

evaluation()中打印预期的消息。然后你不会从这个函数返回任何东西,尽管它被声明为返回int,即你得到未定义的行为。此外,您实际指出随机结果,因为您输出了调用的结果:

std::cout << Thing.evaluation(Thing.getValue()) << std::endl;
顺便说一句,不要使用std::endl!如果您需要换行符,请使用'\n',如果要使用std::flush清除缓冲区。不必要地使用std::endl是主要性能问题的一个相对常见的来源。

相关问题