使用std :: cout

时间:2017-11-05 06:58:50

标签: c++

我无法解决这个问题。

在使用cout之前,我可以看到正确的值。

但是在使用cout后,为什么值会改变?

是由cout引起的吗?

请告诉我为什么......

#include <iostream>
using namespace std;     

/*    
03_CPP_Refer.ppt p27 excercise02    
*/

typedef struct Point {    
    int xpos;    
    int ypos;    
} Point;

Point& pntAddr(const Point &p1, const Point &p2) {
    Point rst;
    rst.xpos = p1.xpos + p2.xpos;
    rst.ypos = p1.ypos + p2.ypos;

    return rst;
}
/*
Point struct add
*/
void ex03_02() {
    Point * p1 = new Point;
    Point * p2 = new Point;

    p1->xpos = 3;
    p1->ypos = 30;
    p2->xpos = 70;
    p2->ypos = 7;

    Point &result = pntAddr(*p1, *p2);

    cout << "[" << result.xpos << ", " << result.ypos << "]" << endl;//correct result [73, 37]

    std::cout << "[" << p1->xpos << ", " << p1->ypos << "]+";
    std::cout << "[" << p2->xpos << ", " << p2->ypos << "]=";
    cout << "[" << result.xpos << ", " << result.ypos << "]" << endl;//incorrect result [ garbage, garbage ]


    delete p1;
    delete p2;
}

void main(int argc, char * argv[]) {
    ex03_02();
}

输出:
[73,37]:正确值
[3,30] + [70,7] = [13629668,13630652]

4 个答案:

答案 0 :(得分:2)

在函数pntAddr中,您将返回对局部变量的引用。这将导致未定义的行为,当然未定义的行为有时可能是预期的结果,但您无法对此进行中继。

答案 1 :(得分:1)

您的函数不应返回对局部变量的引用,因为当函数结束时,它会释放局部变量并返回对它的引用,从而导致未定义的行为。您可以做的是删除引用,而是返回副本。

Point pntAddr(const Point &p1, const Point &p2) {
Point rst;
rst.xpos = p1.xpos + p2.xpos;
rst.ypos = p1.ypos + p2.ypos;

return rst;
}

您也可以通过引用传递一个点并在里面设置值。

void pntAddr(const Point &p1, const Point &p2, Point& rst) {
rst.xpos = p1.xpos + p2.xpos;
rst.ypos = p1.ypos + p2.ypos;
}

然后你可以像这样使用它:

Point rst;
pntAddr(*p1, *p2, rst); // Now rst contains the result

答案 2 :(得分:0)

Point& pntAddr(const Point &p1, const Point &p2) {
Point rst;
rst.xpos = p1.xpos + p2.xpos;
rst.ypos = p1.ypos + p2.ypos;

return rst;
}

在pntAddr函数中,您返回一个局部变量(函数内部声明的变量)所以这样做的是它会在函数结束时立即销毁局部变量。所以,既然没有返回值,它就会返回一个垃圾值。

这就是你获得垃圾价值的原因。

另一个问题是这个

Point &result = pntAddr(*p1, *p2);

在代码块中,这会产生运行时错误。我还没弄清楚原因,所以任何帮助都会受到赞赏。

答案 3 :(得分:-2)

取代:

Point &result = pntAddr(*p1, *p2);

使用:

Point result = pntAddr(*p1, *p2);

这是因为从pntAddr函数中获取结果作为地址,您需要将其存储在指针中或直接映射到变量。