我不知道如何将变量从一个类中的方法传递和检索到另一个类的另一个方法

I dont understand how to pass and retrieve variables from method in one class to other method in other class

本文关键字:方法 另一个 检索 一个 变量 我不知道      更新时间:2023-10-16

我正在编写面向对象的C++程序,我有点吃力。我正在尝试创建一个程序来演示默认和非默认构造函数和指针的使用。我尝试先做默认构造函数。

因此,我只能在一个方法中存储和检索局部变量。但现在我必须将值传递给其他类(我想我必须这样做),然后再次检索信息,但几乎没有修改。

我可以像以前一样将对象初始化为一个类,但当我尝试检索对象时,它基本上只检索空白空间。如何正确地将对象传递给另一个类中的方法,然后将其检索回来?

有指针吗?

Book.cpp

#include <iostream>
#include <sstream>
using namespace std;
#include "Book.h"
Book::Book()
{
}
void Book::setTitle(string  title)
{
    this->title = title;
}
void Book::setAuthorName(string first, string last)
{
    Author author;
    author.setFirstName(first);
    author.setLastName(last);
}

void Book::setPrice(double price)
{
    this->price = price;
}
string Book::convertDoubleToString(double number)
{
    return static_cast<ostringstream*>( &(ostringstream() << number) ) -> str();
}
string Book::getBookInfo()
{
    stringstream ss;
    Author author;
    ss << title << endl << author.getFullName() << endl << "$" << convertDoubleToString(price) << endl;
    return ss.str();
}

无法使用此部件

void Book::setAuthorName(string first, string last)
{
    Author author;
    author.setFirstName(first);
    author.setLastName(last);
}

因为在这个函数中,您创建了一个本地对象,设置了它的值,然后在函数退出时将其销毁。如果要保留此作者信息,则需要在Book类中创建Author类的成员变量。

在你的Book类声明中,你需要这样的

class Book {
    Author m_Author;  // This is your member variable that you can store author data in
};

然后在setAuthorName函数中,设置m_Author的值,而不是创建局部变量。这将保留成员变量m_Author 内的值

作者属于本书。您必须在类Book的构造函数中声明它,这样只要Book存在,它就会存在。

您在方法中声明它,因此它仅在方法执行期间存在。

void Book::setAuthorName(string first, string last)
{
    Author author;
    ...
}

这是一个范围问题。

相关文章: