C++ 意外的数字输出
C++ Unexpected number output
>编辑:由于下面的建议,修复了这个问题。将 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
是导致主要性能问题的相对常见的来源。
相关文章:
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 如何将输出数字划分为奇数和偶数
- 输出错误,问题是找到总和5000位数字cpp
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 字符串比较中的意外输出
- 以C++输出一个数字三角形
- 每次在 c++ 中输出不同(意外行为)
- C++输出奇怪的字符而不是数字 (Windows)
- 一个C++程序,用于在输入位数时输出具有特定位数的 .txt 文件中的所有数字
- 来自 decltype 的意外输出类型
- 反向输出数字 - c++
- 如何将数字输出到文件中,所有数字都具有相同的精度
- 标准输出C++意外行为
- 递归函数用于计算 n 个数字之和的意外输出
- C++ 如何从输入字母或数字输出字母或数字
- 双精度数字程序意外值
- gcc 预处理的表单哈希符号 + 数字"# 1"输出行是什么意思?
- C++ 意外的数字输出
- 数据将奇怪的数字输出到文件,MAP C++