在代码中获取虚拟值C++而不是预期值

getting dummy value in C++ code rather than expected value

本文关键字:C++ 代码 获取 虚拟值      更新时间:2023-10-16

我在理解为什么我的代码为我提供了一些虚拟值时遇到了问题。

有人可以帮助我找出我的错在哪里,原因是什么?

#include <stdio.h>
#include <iostream>
class mypair
{
public:
    int a,b;
public:
    int print (int first , int second)
    {
        a = first;
        b = second;
        std::cout<<a <<" hello "<<b;
    }
    int getmax();
};
int mypair ::getmax()
{
    int res;
    res = (a>b)?a:b;
    std::cout<<res;
    return res;
}
int main ()
{
    mypair abc;
    std::cout<<abc.print(5,6);
    std::cout<<abc.getmax();
}

print() 不返回任何值,但应返回int 。 这是 UB,您的虚拟值是由此引起的。

此外,在print()getmax()中,您都将输出发送到cout 。在 getmax() 的情况下,此输出将立即先于返回值的输出,导致相同的数字显示两次,没有任何空格或分隔符。