【发布时间】:2019-09-10 19:46:04
【问题描述】:
我正在学习 C++,我在作业中遇到了类似的情况。我解决这个案例的每一次尝试都有几个问题,所以我在这里简化了它。
对于这个场景,我将使用这个类:
class Story {
string _title;
//a simple getter
string getTitle(){
return _title;
}
};
现在在我的主函数中,我有stories,一个带有指向Story 的向量的指针:
vector<Story *> * stories = function();
我的目标是访问我的向量中第一个Story 的_title(我的向量大小将始终大于0)。
为此,我尝试了一些我认为可行的方法:
//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 ‘->’ ?)
*/
我明白为什么我的尝试 2 有效,但我不明白为什么 1、1.5 和 3 无效。
以防万一,我使用这些选项进行编译:
--std=c++11 -O0 -ggdb -Wall -Wextra
【问题讨论】:
-
???? #3 看起来像是一个错字。
-
*(stories).at(0)与stories->at(0)不同。(*stories).at(0)是。注意*在()里面,所以意思不同。 -
想象一下,如果
stories->begin()返回第一个Story*,你将如何获得第二个?当然,它必须返回一些你可以增加的东西来获得下一个Story*,这不会是第一个Story*的值,不是吗? -
我刚刚像@Peter 一样尝试了尝试 1 和 1.5。我从来没有注意到
*添加在里面。事实上,@TrebledJ 为尝试 3 “指出”了一个错字,@DavidSchwat 为迭代器提供了解释帮助。谢谢大家。 -
C++ 在值语义上蓬勃发展。不管如何这样做,请不要这样做。
vector可以直接包含故事的内容。