【发布时间】:2013-03-14 19:35:15
【问题描述】:
所以我做了这门课:
class Book
{
public:
Book(string newTitle = "???", string newAuthor = "???");
virtual ~Book();
string getTitle();
string getAuthor();
void setTitle(string newTitle);
void setAuthor(string newAuthor);
virtual string allInfo();
private:
string title;
string author;
};
我打算在另外两个课程中介绍allInfo()-function
一个叫HardcoverBooks,另一个叫AudioBooks。两者都继承自Book。
这是我随后在两个类的 .cpp 文件中所做的,首先是 AudioBook 类:
string AudioBook::allInfo(){
stringstream newString;
newString<<"Title: "<<this->title<<endl<<"Author: "<<this->author<<endl
<<"Narrator: "<<this->narrator<<endl
<<"Length(in minutes): "<<this->length<<endl<<endl;
return newString.str();
}
这在HardcoverBook 类中:
string HardcoverBook::allInfo(){
stringstream newString;
newString<<"Title: "<<this->title<<endl<<"Author: "<<this->author<<endl
<<"Pages: "<<this->pages<<endl<<endl;
return newString.str();
}
一切都很好,花花公子,除了 AudioBook 类抱怨这个:
include\Book.h||在成员函数'virtual std::string 有声书::allInfo()':|包括\Book.h|41|错误:'std::string Book::title' 是私有的| mningsuppgiftIIB\src\AudioBook.cpp|27|错误: 在这种情况下|包括\Book.h|42|错误:'std::string Book::author' 是私有的| mningsuppgiftIIB\src\AudioBook.cpp|27|错误: 在这种情况下| ||=== 构建完成:4 个错误,0 个警告 ===|
但在HardcoverBook 中,它根本没有抱怨这一点,这很奇怪。
我的问题:
我该怎么做才能完成这项工作? (即让两个类都能以自己的方式使用函数
allInfo())为什么不能这样工作?
编辑: 这是我正在做的一些作业,其中一个要求是使成员变量和属性私有。如此受保护确实有效,为那些家伙表示敬意,但我会添加另一个奖励问题:
- 如何使其与私有成员变量一起使用?
【问题讨论】:
-
使
string title;和string author;受保护字段 -
其他人已经回答让他们受到保护。如果您想防止子类修改这些成员,您还可以考虑提供公共访问器。编辑:或者只使用您已经声明的访问器...
-
我正在做这个作为家庭作业,其中一个要求是使成员变量和属性私有。可能应该在发布之前提到这一点。
标签: c++ compiler-errors