class 中的向量在引用的 class 中为空

Vector in class is empty in referenced class

我可以将我的问题浓缩成以下问题:

Class1 x;
Class1 y;
x.Label = "Test";
y = x;
x.myVector.push_back("test");

结果: x.myVector.size() == 1,y.myVector.size() == 0,但都带有“测试”标签!

我对 C++ 比较陌生,但不幸的是我无法通过在互联网上搜索来解决问题...

感谢您的帮助!

Class1 x;
Class1 y;

在这里你正在制作你的两个对象。两者都没有标签和空向量。

x.Label = "Test";

现在 x 有标签 "Test"

y = x;

没有看到 = 是如何为 Class1 实现的,就不可能确定这里发生了什么。如果编译器实现了它,那么它可能只是复制了所有内容,所以现在 yx 都有标签 "Test",并且向量的 none 包含任何内容。

x.myVector.push_back("test");

现在 x.myVector 包含 "Test"。但是,这不会影响 y(或 y.myVector)。这就是为什么 y.myVector.size()0,你没有在里面放任何东西,所以它仍然不包含任何东西。

您的示例远未完成,因此我将假设最简单的编译方法:

// creates an instance named x on the stack
Class1 x; 

// creates an instance named y on the stack
Class1 y; 

// sets the label of the x instance to "Test"
x.Label = "Test"; 

// COPIES all data from x over to y (including the label)
y = x; 

// inserts into the vector of x, as the copy has gone through already, this is in x only
x.myVector.push_back("test"); 

Result: x.myVector.size() == 1, y.myVector.size() == 0, yet both have the label “Test”!

两者应该有相同的标签,因为你有:

x.Label = "Test";
y = x; // 'x' and 'y' are now same...

x 的实例复制到 y... 但是这个:

x.myVector.push_back("test"); // x is now 'test'

在副本之后出现...所以,它仅适用于x而不是y...并且自vectors像大多数 STL 类...

Note: C/C++, in code, goes forward and never looks backward, until and unless the programmer forcibly drags it back using goto, loops, or something similar...


编辑: 您可能认为 references 的内容,所以:

Class1 y;
Class1& x = y;
x.Label = "Test";
// y = x; Eh, redundant statement
x.myVector.push_back("test");

你认为它应该做什么...