相关疑难解决方法(0)

C++ 代码的行为取决于编译器

我对 c 和 c++ 真的很陌生

我试着用结构来创建一个类似列表的结构,基本上可以包含浮点数和列表。

此代码可编译,但其行为因编译器而异:

  • 使用最新版本的visual studio社区,它输出5然后0.

  • 使用在线外壳,我得到5然后5

当向量通过函数时,我想要得到的第二个。

这是代码:

#include <iostream>
#include <vector>

using namespace std;

struct Box {
    Box(char t) {
        type = t;
    }
    union Value {
        float number;
        vector<Box>* elements;
    };
    Value value;
    char type;
};

Box newBox() {
    Box aBox('l');

    vector<Box> newVec;
    newVec.assign(5, Box('n'));


    aBox.value.elements = &newVec;
    cout << aBox.value.elements->size() << "\n";
    return aBox;

}

int main()
{
    Box test = newBox();
    cout << …
Run Code Online (Sandbox Code Playgroud)

c++ struct pointers

0
推荐指数
1
解决办法
61
查看次数

标签 统计

c++ ×1

pointers ×1

struct ×1