下面代码中的注释部分打印了一些不明确的值。
未注释的版本打印:
1:one
这意味着如果我在将对象添加到 vector 之前为类变量赋值,它会打印赋值。但是,如果我在将对象添加到 vector 后分配一个值,它不会打印分配的值。
#include<iostream>
#include<stdio.h>
#include<vector>
#include<string>
using namespace std;
class T
{
public:
string t;
int n;
};
int main()
{
/**
std::vector<T>::iterator it;
vector<T>li;
it = li.begin();
T t1;
it = li.insert(it,t1);
t1.n = 1;
t1.t = "one";
it = li.begin();
T t2;
it = li.insert(it+1,t2);
it = li.begin();
T t3;
it = li.insert(it+2,t3);
cout << li.at(0).n << ":" << li.at(0).t << endl;
*/
std::vector<T>::iterator it;
vector<T>li;
it = li.begin();
T t1;
t1.n = 1;
t1.t = "one";
it = li.insert(it,t1);
it = li.begin();
T t2;
it = li.insert(it+1,t2);
it = li.begin();
T t3;
it = li.insert(it+2,t3);
cout << li.at(0).n << ":" << li.at(0).t << endl;
}
对于 Java,情况并非如此。相反,无论在将对象添加到 vector 之前或之后分配成员变量,都会打印该值。如何实现类似 Java 的功能?
最佳答案
C++ 中的
struct
或 class
的行为与任何其他类型一样。它们只是一组类型。所以当你声明T t1;
时,编译器看到的几乎就像
// grouped together in the name `t1`
string t;
int n;
因此,当您在 vector 中发送 t1
时,它所做的与它在 java 中对 int
所做的完全相同,它会复制它。
你能做些什么来对抗它?
有两种解决方法。您可以像这样更改 vector 内的 T
的值:
li[0] = {"aString", 23}
或者您可以插入指针。指针就像java中的对象。其实java中的对象都是指针,只是值是隐藏的。它看起来像这样:
vector<unique_ptr<T>> li;
// make unique is just a wrapper around the new to make a std::unique_ptr
li.emplace_back(make_unique<T>("aString", 23));
我真的建议您使用 emplace_back
而不是迭代器和 insert
。它将使您的代码更干净、更快。
关于c++ - C++中的类变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33900529/