【发布时间】:2020-05-14 11:53:04
【问题描述】:
(问题已解决,解决方案已作为注释行添加到 main.cpp)
main.cpp 文件中描述了我遇到的问题。我已经检查了有关此的其他问题,但没有一个真正有帮助。
我正在尝试使用 C++ 创建一个控制台应用程序,您可以在其中将 BOOKS 添加到 LIBRARY。在 library 类中,有一个 displayInfo() 函数可以显示特定书籍的信息。它可以显示整数或双值信息而不会出现问题,但是当我尝试显示字符串类型的信息时它会出现问题。它只是打印空白。让我给你一些我的代码示例。
这是 Book.h
#ifndef BOOK_H
#define BOOK_H
#include <string>
class Book
{
friend class Library;
public:
void setName();
std::string getName();
private:
std::string nameOfBook;
};
#endif
Book.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;
}
Library.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
Library.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;
}
还有 main.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 book\n"
<< "Press 2 to display info\n"
<< "Press 0 to quit\n";
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 input\n";
continue;
}
}
}
编辑: 我用 VS Code 对此进行了编码,并在必要时用 MinGW (8.2.0) 对其进行了编译。
【问题讨论】: