[英]Accessing a member function from a vector of pointers? C++
So, lets say I have a vector, vector<Item*> vItem
and an Item class with a member function Item::setValue();
因此,假设我有一个向量
vector<Item*> vItem
和一个具有成员函数Item::setValue();
的Item类Item::setValue();
. 。 Lets also say I populated that vector by using
vItem.push_back(new Item)
. 还可以说我使用
vItem.push_back(new Item)
填充了该向量。
Now, to access that member function, through the pointer in the vector, would vItem[0]->setValue("key");
现在,通过向量中的指针访问该成员函数,将是
vItem[0]->setValue("key");
. 。 be valid?
有效吗? I assumed it was, however when I
cout
the member variables using a getValue()
function, nothing new is returned, only the default values from my constructor. 我以为是,但是当我使用
getValue()
函数cout
成员变量时,没有返回任何新内容,仅返回构造函数中的默认值。
Any ideas? 有任何想法吗? I feel like it's a stupid mistake in my logic, but I'm not sure.
我觉得这是我逻辑上的一个愚蠢错误,但我不确定。 Any help would be greatly appreciated.
任何帮助将不胜感激。
EDITS: 编辑:
setValue code: setValue代码:
void Item::setValue(string sValue)
{
m_sValue = sValue;
}
with the private variable: 与私有变量:
string m_sValue;
getValue code: getValue代码:
string Item::getValue()
{
return m_sValue;
}
Simple version of the code: 简单版本的代码:
void func2(vector<Item*>& vItem)
{
vItem.push_back(new Item);
vItem[0]->setValue("key");
}
int main(int argc, char * argv[])
{
vector<Item*> vItem;
func2(vItem);
cout << vItem[0]->getValue() << endl;
return 0;
}
I should also note: everything compiles just fine (g++ using c++0x standard) however, the setter just doesn't set. 我还应该注意:一切都可以正常编译(使用c ++ 0x标准的g ++),但是setter却没有设置。
Your getValue returns a void and there's an out-of-place semi-colon after getValue()
in your implementation of that method. 您的getValue返回一个空值,并且在该方法的实现中,在
getValue()
之后有一个分位的分号。 Change to string Item::getValue(){return m_sValue;}
更改为
string Item::getValue(){return m_sValue;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.