c++ - C++中的类变量赋值

标签 c++

下面代码中的注释部分打印了一些不明确的值。

未注释的版本打印:

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++ 中的

structclass 的行为与任何其他类型一样。它们只是一组类型。所以当你声明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/

相关文章:

c++ - Microsoft Active Accessibility、VB6 和 Ranorex

c++ - std::unique 与谓词比较 std::string 不删除重复项

c++ - 如何使用 boost.python 导出复杂类

C++ 和 SDL2 - "Auto-Generate"使用了 DLL?

c++ - Qt 多页 TIFF

c++ - 如何从 C++ 中的 std::ifstream 获取文件路径

c++ - C++ 中的 "-->"运算符是什么?

c++ - 将 main 声明为 extern "C"是否合法 C++?

c++ - 编译器将如何优化临时对象?

c++ - 结构体中的指针和字符