如何将对象存储在矢量中的对象中? (C ++)

时间:2014-03-17 07:26:12

标签: c++ string class object vector

我希望这不是一个愚蠢的问题。基本上我想在Statement类型的向量中访问存储在类(Statement是我正在使用的名称)中的字符串。基本上我试图将对象存储在动态的对象层次结构中。 Types.cpp:

#include<iostream>
#include<fstream>
#include <string>
#include <vector>
using namespace std;

class Statement{

public:
vector<string> Inner_String;
vector<Statement> Inner_Statement;
string contents;

void set_contents (string);
string get_contents(){ return contents;}
void new_string(string);
string get_string(int v){return Inner_String[v];}
void new_Inner_Statement(Statement);
Statement get_Inner_Statement(int v){return Inner_Statement[v];}
};

void Statement::set_contents(string s){
contents = s;
}

void Statement::new_string(string s){
Inner_String.push_back(s);

}
void Statement::new_Inner_Statement(Statement s){
Inner_Statement.push_back(s);
}

主要方法:

#include <iostream>
#include "FileIO.h"
#include "Types.h"

using namespace std;
int main()
{
Statement test;
test.new_Inner_Statement(Statement());
Statement a = test.get_Inner_Statement(0);
a.set_contents("words");
cout << a.get_contents();
test.get_Inner_Statement(0).set_contents("string");
cout << test.get_Inner_Statement(0).get_contents();
return 0;
}

会发生什么      cout&lt;&lt; a.get_contents() 返回其字符串      cout&lt;&lt; test.get_Inner_Statement(0).get_contents() 没有。

1 个答案:

答案 0 :(得分:2)

看看这段代码:

test.get_Inner_Statement(0).set_contents("string");
^^^^^^^^^^^^^^^^^^^^^^^^^^^

它调用此函数:

Statement get_Inner_Statement(int v)

返回类型语句的复制对象(临时)。在此对象上,您调用set_contents函数,该函数在调用结束时不再存在。

然后,你打电话:

test.get_Inner_Statement(0).get_contents();

从未更改的语句创建一个新的临时文件,并尝试获取其内容。

相关问题