我正在学习C ++,在我的作业中遇到了类似的情况。我尝试解决此问题的每一个尝试都带有一些问题,因此我在这里进行了简化。
在这种情况下,我将使用此类:
class Story {
string _title;
//a simple getter
string getTitle(){
return _title;
}
};
现在在我的主函数中,我有stories
,这是一个指向Story
的向量的指针:
vector<Story *> * stories = function();
我的目标是访问向量中第一个_title
的{{1}}(向量大小将始终大于0)。
为此,我尝试了一些我认为可行的方法:
Story
我了解为什么我的尝试2有效,但是我不明白为什么1、1.5和3无效。
以防万一,我使用以下选项进行编译:
//Attempt 1 (doesn't work)
*(stories)[0]->title();
//I thought `*(stories)[0]` returns the first `Story*`
/** Error message:
* error: ‘class std::vector<Story*>’ has no member named ‘title’
*/
//Attempt 1.5 (equivalent to Attempt 1)
*(stories).at(0)->title();
//Attempt 2 (works)
stories->at(0)->title();
//Aren't `*(stories).at(0)` and `stories->at(0)` the same?
//Since Attempt 1.5 failed, there as to be a difference..
//Attempt 3 (doesn't work)
stories->begin()->title();
//I thought `stories->begin()` returns the first `Story*`
/** Error message:
* error: request for member ‘title’ in
* ‘* stories->std::vector<Story*>::begin().__gnu_cxx::__normal_iterator<Story**, std::vector<Story*> >::operator->()’, which is of pointer type ‘Story*’
* (maybe you meant to use ‘->’ ?)
*/