EDIT: Fixed the problem thanks to advice from below. Changed the return type of evaluation() from an int to a void.
I'm learning how to use classes, and I'm experiencing a problem. I keep getting an output that says:
0
They are not equal.
4469696
Where is that last number coming from? It should be somewhere after the line
std::cout << Thing.evaluation(Thing.getValue()) << std::endl;
but I don't see anything that could possibly be outputting that value. Is it memory leakage?
#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;
}
In evaluation()
you print the expected messages. Then you don't return anything from this function although it is declared to return int
, ie, you get undefined behavior. Further more, you actually point the random result since you output the result of the call:
std::cout << Thing.evaluation(Thing.getValue()) << std::endl;
BTW, don't use std::endl
! If you want a newline, use '\\n'
, if you want to flush the buffer use std::flush
. Unnecessary use of std::endl
is a relatively frequent source of major performance problems.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.