虚函数错误
Virtual functions error?
所以我创建了这个类:
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()
-函数一个叫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
类抱怨这个:
includeBook.h||In成员函数'virtual std::stringAudioBook::allInfo()':| includeBook.h|41|error: 'std::string .Book::title' is private| mningsupgiftiib src audiobbook .cpp|27|错误:在此上下文中|包括Book.h|42|error: 'std::stringBook::author' is private| mningsupgiftiib src audiobbook .cpp|27|错误:在此上下文中|| |===构建完成:4个错误,0个警告===|
但是在HardcoverBook
中,它根本没有抱怨这个,奇怪的是。
我的问题:
我该怎么做才能使它工作?(即使两个类都能够以自己的方式使用
allInfo()
函数)为什么不能这样工作?
编辑:这是我正在做的一些功课,其中一个要求是使成员变量和属性私有。所以保护是有效的,为那些家伙感到骄傲,但我要添加另一个额外的问题:
- 我如何使它与私有成员变量的工作?
title
和author
成员为private
。这意味着它们在子类中是不可见的,比如AudioBook
。
为了使它们对子类可见,你需要将这些成员设置为protected
而不是private
。
另一种选择是将成员字段保留为私有,并添加受保护或公共访问方法以允许读取这些值。例如:
public:
string getAuthor()
{
return author;
}
我也会评论说,我不明白为什么你使用this->
来访问你的类的成员。没有必要这样做,通常最好省略它。
没有看到你的家庭作业,我不能100%确定如何理解
成员变量和属性是私有的
我猜你的任务是覆盖allInfo()
。您被要求扩展返回的string
,以包含基类实现所包含的所有信息,并添加更多信息。
您当前的尝试只是复制Book::allInfo()
中的代码。这就是问题所在。为了实现这一点,派生类需要访问私有成员。你不能这么做。因此,您的解决方案必须涉及在基类上调用allInfo()
,然后附加到基类实现返回的字符串上。
由于这是作业,我将避免为您实现它!
让成员protected
通过派生类访问它们:
protected:
string title;
string author;
否则,它们对于派生类是不可见的。
私有和受保护成员:
类a的Public成员可供所有人访问。
受保护的成员在a的代码之外是不可访问的,但是可以从a派生的任何类的代码中访问。
Private类a的成员在a代码之外是不可访问的,或从a派生的任何类的代码中获取。
如果您想让它们保持private
,另一种方法是为它们创建protected
或public
访问方法
您应该将private
成员转换为:
protected:
string title;
string author;
- 链接器错误:函数的多个定义
- 编译器错误:函数调用在常量表达式中必须有一个常量值
- 错误:函数声明符之后的预期函数体
- C 错误 - 函数不能超载
- 如何修复传递参数时调用错误函数的主函数?(C++)
- 错误:函数调用中有两个参数
- 错误:函数不是“类”的静态数据成员 - C++
- C ,G 编译错误函数
- CMake 解析错误函数缺少结尾")"。而是找到带有文本的未终止字符串")
- C++ 错误 函数 2 的多重定义
- 错误:函数调用中从int到int(*)[4]的转换无效
- C++14 自动扣除错误:函数返回一个数组
- 视觉C++错误:函数必须返回一个值
- 错误:函数声明中的两种或多种数据类型
- 错误:函数未在作用域中声明
- rtw_android.c错误:函数“strnicmp”的隐式声明[-Weror=隐式函数声明]
- 错误:函数中的return语句没有值,返回“void*”[-fpermission]
- 简单程序中的链接器错误:函数的多重定义
- 错误:函数参数太多
- 错误:函数__tmaincrtstartup中引用的未解析的外部符号_main