C++指针赋值(指向向量)

发布于 2024-10-19 13:25:21 字数 488 浏览 1 评论 0原文

这是我在任何论坛上发表的第一篇文章,所以请耐心等待。

我正在编写一个 C++ 程序,该程序使用自定义类“Book”,其中包含存储在字符串中的成员变量,例如标题、作者和其他变量。这些成员变量中有一个向量,用于存储 Review 类型的对象(这是另一个自定义类)。现在,在我的驱动程序文件(main() 所在的位置)中,需要访问该向量(每个 Book 对象中的 Reviews 向量)并对其进行更改。我意识到我需要利用向量类型的指针 (例如。 矢量指针名称 )。所以我向 Books 类添加了另一个成员变量,它是一个指针。我面临的问题是将指针指向向量。我可以在哪里做这个作业?我尝试取消引用它并将其指向该对象的默认构造函数中的向量,但这会导致我的程序在运行时崩溃而不会引发异常。我在构造函数中放入的行是 *指针=评论向量;

我是这个论坛的新手,仍在学习如何在这里发帖,所以如果我在帖子中犯了错误,或者我的信息不清楚或不充分,请耐心等待。如果我需要发帖或说更多内容以明确我的立场,请告诉我。

谢谢。

This is my first post in any forum so please bear with me.

I am writing a C++ program that utilizes a custom class 'Book' with member variables such as title, author and other variables that are stored in strings. Amongst these member variables is a vector for storing objects of type Review (which is another custom class). Now in my driver file (where the main() is located) needs to access that vector (the Reviews vector in each Book object) and make changes to it as well. I realized that I need to utilize a pointer of type vector
(eg.
vector pointerName
). So I added another member variable to the Books class which is a pointer. The problem I am facing is to point that pointer to the vector. Where can I make this assignment? I tried de-referencing it and pointing it to the vector in the default constructor for the object, but that causes my program to crash at run time without throwing an exception. The line I put in the constructor is
*pointer = vector_of_reviews;

I am new to this forum and still learning how to go about posting here so please bear with me if I have made a mistake in my post or if I was unclear or insufficient with my information. Please let me know if I need to post or say anything more to make my stance clear.

Thank You.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我的痛♀有谁懂 2024-10-26 13:25:21

要分配一个指针来“指向”对象的实例,请使用pointer = &vector_of_reviews

的&运算符获取某个内容的地址,而您想要将其分配给指针。

*pointer = vector_of_reviews 取消引用指针(获取“指向”的实际对象)。如果指针尚未初始化,这很可能会崩溃。如果指针有效,这将执行赋值操作,即。调用向量类的赋值运算符。

To assign a pointer to 'point to' an instance of an object use pointer = &vector_of_reviews.

The & operator gets the address of something, and it's this that you want to assign to the pointer.

*pointer = vector_of_reviews dereferences the pointer (obtains the actual object 'pointed to'). This would more than likely crash if the pointer is yet to be initialised. If the pointer was valid this would perform a value assignment, ie. invoke the vector class's assignment operator.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文