在C ++代码得到虚值,而不是预期值

问题描述 投票:1回答:1

我有理解的是,为什么我的代码为我提供一些虚拟的价值问题。

有人可以帮助我,我错在何处以及是什么原因?

#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();
}
c++ eclipse iostream
1个回答
4
投票

print()不返回任何值,但将返回一个int。这是UB,你的虚拟价值是由这个引起的。

此外,在这两个print()getmax()您发送输出到cout。在getmax()的情况下,该输出将立即predede返回值的输出,从而导致没有任何空间或分离器将被显示两次相同的编号。

© www.soinside.com 2019 - 2024. All rights reserved.