如何使用基类的数据成员作为派生类的构造函数?(C++)

How to Use data members of base class as derived class' constructor? (in C++)

本文关键字:构造函数 C++ 基类 何使用 数据成员 派生      更新时间:2023-10-16

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

#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();
}

创建这个派生的类构造函数似乎是我的错?

您写的内容:

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

mybook(字符串t,字符串A,int p):书(标题,作者)是错误的标题和作者在那里没有认可。使用T和A: mybook(字符串T,字符串A,INT P):书籍(t,a)