【问题标题】:How to Use data members of base class as derived class' constructor? (in C++)如何使用基类的数据成员作为派生类的构造函数? (在 C++ 中)
【发布时间】:2017-12-21 01:41:40
【问题描述】:

我正在尝试使用基类的数据成员作为派生类的构造函数,但是每当我尝试运行程序时似乎都会出错。以下是我的代码:

#include <iostream>
using namespace std;

class Book
{
protected:
    string title;
    string author;
public:
    Book(string t, string a)
    {
        title = t;
        author = a;
    }
};

class MyBook: public Book
{
protected:
    int price;
public:
    MyBook(string T, string A, int P): Book(title, author)
    {

        price = P;
    }
    void display()
    {
        cout << "Title: " << title << endl;
        cout << "Author: " << author << endl;
        cout << "Price: " << price << endl;
    }
};
int main()
{
    MyBook One("abc", "def", 2);
    One.display();
}

我在创建这个派生类的构造函数时似乎有什么错?

【问题讨论】:

  • 请勿标记垃圾邮件,除非您试图引起对您的问题的负面关注。
  • Please do not tag multiple languages in your question 除非您的问题专门针对这些语言。您可能认为它会导致更快的答案,但现实情况是它更有可能导致更快的关闭。
  • 好的,知道了。实际上我第一次使用堆栈溢出。我并不急于回答,我只是编程方面的初学者,只是自学。生活在多么美好的世界。感谢您的建议。

标签: c++ oop


【解决方案1】:

你写的:

MyBook(string T, string A, int P): Book(title, author)

我猜你真正想要的:

MyBook(string T, string A, int P): Book(T, A)

:Book(T, A) 部分是将参数传递给基类构造函数。此处未定义titleauthor,但定义了TA

一个可能的混淆来源是titleauthor 恰好是基类中使用的名称。您应该注意,您将信息从派生类构造函数传递到基类构造函数,而不是相反。所以派生类构造函数应该告诉基类构造函数TA

【讨论】:

  • @Jayy 您可以考虑对您认为有帮助的每个答案进行投票,并将最好的答案“勾选”为“已接受”。这就是这个网站的运作方式。
【解决方案2】:

MyBook(string T, string A, int P): Book(title, author) 错误 标题和作者在那里不被识别。使用 T 和 A: MyBook(string T, string A, int P): Book(T, A)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2014-01-21
    • 2020-08-21
    • 2015-08-18
    • 2021-02-14
    • 2015-01-05
    相关资源
    最近更新 更多