C++ 意外的数字输出

C++ Unexpected number output

本文关键字:数字输出 意外 C++      更新时间:2023-10-16

>编辑:由于下面的建议,修复了这个问题。将 EVALUATION() 的返回类型从 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;
}

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

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

顺便说一句,不要使用std::endl!如果需要换行符,请使用 'n' ,如果要刷新缓冲区,请使用 std::flush 。不必要地使用 std::endl 是导致主要性能问题的相对常见的来源。