我不知道如何将变量从一个类中的方法传递和检索到另一个类的另一个方法
I dont understand how to pass and retrieve variables from method in one class to other method in other class
我正在编写面向对象的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;
...
}
这是一个范围问题。
相关文章:
- C++从另一个类访问公共静态向量的正确方法是什么
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 在另一个类视图中添加最多2个图表的正确方法是什么
- 检查哪个对象调用了另一个对象的对象方法
- 不能将方法返回的值用于另一个方法
- Qt将信号与另一个类方法连接
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 将一个类的方法指针存储到另一个类中
- 从另一个标头中的标头调用静态方法
- 无法"this"指针传递到另一个类并在 CPP 中调用该类的任何方法
- C++ |DLL / EXE - 如何从导出的类调用另一个类方法?
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 如果类"A"具有指向另一个类的指针,则"B" A 可以访问 B 类公共方法
- 如何在另一个类中使用类成员的正确方法?
- 重写另一个方法 [C++] 使用的超类回调函数
- 如何构造一个类型特征,可以判断一个类型的私有方法是否可以在另一个类型的构造函数中调用?
- 如何启用使用另一个类的静态方法的模板函数的自动推导,从而消除冗长的调用方代码
- 覆盖作为另一个类的好友的虚拟受保护方法
- 将vector<vector<double>>从x86平台中创建的一个进程发送到x64中构建的另一个进程的最快方法是什么
- 返回一个引用C++中另一个类对象的对象的有效方法