【发布时间】:2012-03-27 17:01:41
【问题描述】:
我目前正在学习类,但我的类实现文件有问题。
在我的类头/规范文件 Book.h 中,我有公共成员函数 setPages。
#ifndef BOOK_H
#define BOOK_H
#include <string>
#include "Author.h"
#include "Publisher.h"
class Book
{
private:
std::string _title;
std::string _edition;
int _pages;
int _copyrightYear;
Author _author;
Publisher _publisher;
public:
Book (std::string title, Author author, Publisher publisher)
{_title = title; _author = author; _publisher = publisher;}
void setPages (int pages);
void setCopyYear (int copyrightYear);
void setEdition (std::string edition);
std::string getTitle () const;
std::string getEditon () const;
int getPages () const;
int getCopyYear () const;
Author getAuthor () const;
Publisher getPublisher () const;
};
#endif
在我的 Book.cpp 实现文件中
#include <string>
#include "Author.h"
#include "Publisher.h"
#include "Book.h"
void Book::setPages (int pages)
{
_pages = pages;
}
我不断收到 Book 不是类名或命名空间的错误消息,但我看不出我做错了什么。我包含了我的 Book 头文件并检查以确保课堂上的所有内容都拼写正确。我在其他课程中也做过同样的事情,而且效果很好,所以我不明白为什么会这样。
任何帮助表示感谢。
这里是Publisher.h 和Author.h
#ifndef PUBLISHER_H
#define PUBLISHER_H
class Publisher
{
private:
std::string _name;
std::string _address;
std::string _phoneNumber;
public:
Publisher (std::string& name)
{_name=name;}
void setAddress (std::string address);
void setNumber (std::string phoneNumber);
std::string getAddress () const;
std::string getNumber () const;
bool operator==(std::string name)
{
if (_name == name)
return true;
else
return false;
};
#endif
和作者.H
#ifndef AUTHOR_H
#define AUTHOR_H
class Author
{
private:
std::string _name;
int _numberOfBooks;
public:
Author(std::string& name)
{_name = name;}
void setNumOfBooks (int numberOfBooks);
int getNoOfBooks () const;
bool operator==(std::string _name)
{
if (this->_name == _name)
return true;
else
return false;
}
};
#endif
【问题讨论】:
-
Author.h和Publisher.h包含哪些文件?如果其中任何一个包含book.h,则您在包含中存在循环依赖关系。 -
还有:
Book (const std::string& title, const Author& author, const Publisher& publisher) : _title(title), _author(author), _publisher(publisher) {} -
尝试在 Booh.h 文件中将
#include "Author.h"和#include "Publisher.h"替换为class Author;和class Publisher;。 -
或者,在 C++11 中,
Book(std::string title, Author author, Publisher publisher) : _title(std::move(title)), _author(std::move(author)), _publisher(std::move(publisher)) {}。注意每个参数都是按值传递的!! -
bool operator==(std::string name)in "Publisher.h" 在您的示例中缺少大括号。这实际上是在您的代码中还是复制和粘贴错误?