对象数组打印空白字符串



(该问题已解决,解决方案已作为注释行添加到main.cpp(

我遇到的问题在主文件中描述.cpp。我已经检查了另一个关于这个问题的问题,但没有一个真正有帮助。

我正在尝试创建一个C++控制台应用程序,您可以在其中将书籍添加到库中。在库类中,有一个displayInfo(( 函数,用于显示特定书籍的信息。它可以显示整数或双值信息而不会出现问题,但是当我尝试显示字符串类型化信息时遇到问题。它只是打印空白。让我给你一个我的代码的小例子。

这是书。

#ifndef BOOK_H
#define BOOK_H
#include <string>
class Book
{
friend class Library;
public:
void setName();
std::string getName();
private:
std::string nameOfBook;
};
#endif

书.cpp

#include "Book.h"
#include <iostream>
#include <string>
using namespace std;
void Book::setName()
{
string nameOfBook;
cout << "Please enter the name of the book: ";
cin >> nameOfBook;
this->nameOfBook = nameOfBook;
}
string Book::getName()
{
return nameOfBook;
}

图书馆.h

#ifndef LIBRARY_H
#define LIBRARY_H
#include "Book.h"
#include <array>
class Library
{
private:
std::array <Book , 10> bookArray; // I have to use this
public:
void addBook();
void displayInfo();
};
#endif

图书馆.cpp

#include "Library.h"
#include "Book.h"
#include <iostream>
#include <string>
#include <array>
using namespace std;
void Library::addBook()
{
bookArray[0].setName();
}
void Library::displayInfo() 
{
cout << "The book: " << bookArray[0].getName() << endl;
}

和主要.cpp

#include <iostream>
#include "Book.h"
#include "Library.h"
#include <string>
#include <array>
using namespace std;
int main()
{
// The problem is solved
// Create the objects out of the loop
// Library obj1 <---- this solved it
while (true)
{
int number; // Ask user what to do
cout << "Press 1 to add a bookn"
<< "Press 2 to display infon"
<< "Press 0 to quitn";
cin >> number;
if (number == 1) // Add a book
{
Library obj1; // <------ THIS IS WRONG
obj1.addBook(); // Consider we named the book as 'Fly'
}
else if (number == 2)   
{
Library obj1; // <------ THIS IS WRONG
obj1.displayInfo(); // ******* The output I'm expecting is The Book: Fly
// But instead, it only gives me The Book:
// I have 4 more strings like this in the main project and all of them have the same problem
}
else if (number == 0) // Everything else
{
break;
}
else
{
cout << "Wrong inputn";
continue;
}
}
}

编辑: 我用VS Code编写了代码,如果重要的话,我用MinGW(8.2.0(编译了它。

代码中的一个问题是你有很多库类的实例,所以addBook登陆一个对象,displayInfo在新对象中(空的(中

您必须:

int main()
{
Library obj1; // declare the lib in scope for all the cases
while (true)
{
int number; // Ask user what to do
cout << "Press 1 to add a bookn"
<< "Press 2 to display infon"
<< "Press 0 to quitn";
cin >> number;
if (number == 1) // Add a book
{
obj1.addBook(); // Consider we named the book as 'Fly'
}
else if (number == 2)   
{
//Library obj1;
obj1.displayInfo(); // ******* The output I'm expecting is The Book: Fly
// But instead, it only gives me The Book:
// I have 4 more strings like this in the main project and all of them have the same problem
}
else if (number == 0) // Everything else
{
break;
}
else
{
cout << "Wrong inputn";
continue;
}
}
}

您将在循环的每次迭代中再次创建对象。 因此覆盖已命名的旧对象。