编辑:通过以下建议修复了问题.将evaluate()的返回类型从int更改为void.
我正在学习如何使用课程,而且我遇到了一个问题.我一直得到一个输出说:
0
They are not equal.
4469696
Run Code Online (Sandbox Code Playgroud)
最后一个号码来自哪里?它应该在线之后的某个地方
std::cout << Thing.evaluation(Thing.getValue()) << std::endl;
Run Code Online (Sandbox Code Playgroud)
但我没有看到任何可能输出该值的东西.是内存泄漏吗?
#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;
}
Run Code Online (Sandbox Code Playgroud)
在evaluation()您打印预期的消息.然后你不会从这个函数返回任何东西,虽然它被声明返回int,即你得到未定义的行为.此外,您实际指出随机结果,因为您输出了调用的结果:
std::cout << Thing.evaluation(Thing.getValue()) << std::endl;
Run Code Online (Sandbox Code Playgroud)
顺便说一句,不要用std::endl!如果您想要换行,请使用'\n',如果要刷新缓冲区使用std::flush.不必要的使用std::endl是主要性能问题的相对频繁的来源.
| 归档时间: |
|
| 查看次数: |
141 次 |
| 最近记录: |