虚函数错误

Virtual functions error?

本文关键字:错误 函数      更新时间:2023-10-16

所以我创建了这个类:

    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中,它根本没有抱怨这个,奇怪的是。

我的问题:

  1. 我该怎么做才能使它工作?(即使两个类都能够以自己的方式使用allInfo()函数)

  2. 为什么不能这样工作?

编辑:这是我正在做的一些功课,其中一个要求是使成员变量和属性私有。所以保护是有效的,为那些家伙感到骄傲,但我要添加另一个额外的问题:

  1. 我如何使它与私有成员变量的工作?

titleauthor成员为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,另一种方法是为它们创建protectedpublic访问方法

您应该将private成员转换为:

protected:
    string title;
    string author;