所以我做了這個類:虛擬功能錯誤?
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||In member function 'virtual std::string AudioBook::allInfo()':| include\Book.h|41|error: 'std::string Book::title' is private| mningsuppgiftIIB\src\AudioBook.cpp|27|error: within this context| include\Book.h|42|error: 'std::string Book::author' is private| mningsuppgiftIIB\src\AudioBook.cpp|27|error: within this context| ||=== Build finished: 4 errors, 0 warnings ===|
但在HardcoverBook
它並不抱怨這一點,奇怪的是。
我的問題:
我該怎麼做,使這項工作? (即,使這兩個類能夠以他們自己的方式使用功能
allInfo()
)爲什麼它不能這樣工作?
編輯: 這是一些功課,我做的,其中一個要求是使成員變量和屬性私人。所以保護沒有工作,爲那些傢伙的榮譽,但我會添加另一個獎金問題:
- 如何使它與私有成員變量一起工作?
使'字符串標題;'和'字符串作者;'受保護的字段 – varnie 2013-03-14 19:37:18
其他人已經回答,使他們受到保護。如果你想阻止子類修改這些成員,你也可以考慮提供公共訪問器。 編輯:或者只是使用你已經聲明的訪問器... – 2013-03-14 19:40:37
我這樣做是作業,其中一個要求是使成員變量和屬性保密。應該在發佈之前提到這一點。 – user1770094 2013-03-14 19:43:34