构造者问题

时间:2012-11-07 19:56:25

标签: c++ visual-c++

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

  

错误C2512:'预订':没有合适的默认构造函数

我做错了什么?

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

4 个答案:

答案 0 :(得分:1)

您的Library类有一个Book数组作为其成员。所有成员必须在施工时进行初始化。由于您没有显式调用Book构造函数,因此假定为默认值(实际上对于数组,它是唯一可以调用的数组)。但是Book没有默认构造函数,因此编译错误。

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

查看代码,声明一个(内联)无参数构造函数

Book();

但是没有定义它,所以编译器找不到它。

尝试例如

Book() {};

- 这只是创建一个无参数的无参数构造函数 - 这就是你的意思吗?

编辑 - 刚看到wnraman回复。这可能更合适,因为无参数构造函数将Book初始化为可能是合理的默认值

答案 3 :(得分:0)

我假设你的代码中还有其他地方像

这样的行
Book book;

或定义了一个书籍数组,或者将它与一些e-g一起使用。 List-来自库的类,它需要一个默认的构造函数,它没有在您的类中定义。要么定义这样的默认构造函数(不带args),要么在代码的其余部分找到有问题的地方......

相关问题