gpt4 book ai didi

c++ - 构造函数问题

转载 作者:行者123 更新时间:2023-11-28 00:52:36 25 4
gpt4 key购买 nike

我必须实现一个类来表示图书馆的书籍。对于每本书,我必须指定:标题、作者、ISBN 代码、出版年份和价格。然后我需要创建一个包含图书馆中所有书籍的数组。这是我处理过的代码,这是错误:

error C2512: 'Book' : no appropriate default constructor available

我做错了什么?

    Book.h
#ifndef BOOK_H
#define BOOK_H

#include<string>

using namespace std;

class Book
{
private:
string title;
string author;
string code;
string edit;
int year;
double price;
public:
Book();
Book(string t, string a, string c, string e, int y, double p)
{
title=t;
author=a;
code=c;
edit=e;
year=y;
price=p;
}
string GetTitle() const { return title;}
string GetAuthor() const { return author;}
string GetCode() const {return code;}
string GetEdit() const {return code;}
int GetYear() const {return year;}
double GetPrice() const {return price;}
};
#endif




Library.h
#ifndef LIBRARY_H
#define LIBRARY_H
#include"Book.h"
#include<iostream>

class Library
{
private:
Book books[50];
int index;
public:
Library()
{
index=0;
}
void Add(Book book)
{
books[index]=book;
index++;
}
void PrintAll()
{
for (int i = 0; i < index; i++)
{
Book book=books[i];
cout<<book.GetTitle()<<":"
<<book.GetAuthor()<<":"<<book.GetYear()<<endl;
}
}
};
#endif

main.cpp


#include"Library.h"
int main()
{
Library library;
Book b1("title1","author1","code1","edit1",1900,34.5);
library.Add(b1);
Book b2("title2","author2","code2","edit2",1990,12);
library.Add(b2);
library.PrintAll();
}

最佳答案

现在,由于您已经定义了一个带有 6 个参数的构造函数,因此编译器不会为您生成默认构造函数。因此,您还需要定义一个默认构造函数来支持诸如 void Add(Book book) {} 之类的代码行。可能如下所示:

Book() : title(""), author(""), code(""), edit(""), year(1900), price(0.0) 
{}

关于c++ - 构造函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13277199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com