似乎我没有正确传递对象的指针,但为什么呢?

It seems like I'm not passing pointers of objects correctly, but why?

本文关键字:指针 对象 为什么呢      更新时间:2023-10-16

我正在使用对象的指针,并能够使用它们的内存地址来传递和检索信息。

我的程序只传递了书名,没有其他信息,我不知道为什么。

如何使该程序正确存储和检索信息?我正在使用指针来传递值,我应该更改主函数以外的其他内容吗?

这是我的主.cpp文件:

#include <iostream>
#include <string>
using namespace std;
#include "Book.h"
int main()
{
    system("cls");
    Author *pAuthor = new Author("John", "Doe");
    Publisher *pPublisher = new Publisher("Wrox", "10475 Crosspoint Blvd.", "Indianapolis");
    Book *pBook = new Book("Memory Management", pAuthor, pPublisher, 39.99);
    cout << pBook->getBookInfo() << endl;
    system("pause");
    return 0;
};

book.cpp文件:

#include <iostream>
#include <sstream>
using namespace std;
#include "Book.h"
Book::Book()
{
}
Book::Book(string title, Author *pAuthor, Publisher *pPublisher, double price)
{
    this->title = title;
    this->price = price;
}
Book::~Book()
{
}

您将pAuther和pPublisher传递给Book构造函数,但不对它们执行任何操作。

Book::Book(string title, Author *pAuthor, Publisher *pPublisher, double price)
{
    this->title = title;
    this->price = price;
}

在这里,你传递指针,但不使用它们。

您的book()构造函数需要使用pAuthor和pPublisher中的数据调用setAuthorName和setPublisher函数。