注意:候选:MyClass:MyClass(const MyClass&) 错误



我的C++程序在保存时出现以下错误:

hw.cpp|10 col 7 error| note: candidate: Category::Category(const Category&) [cpp/gcc]
hw.cpp|10 col 7 error| note:   candidate expects 1 argument, 0 provided [cpp/gcc]
hw.cpp|14 col 9 error| note: candidate: Category::Category(std::__cxx11::string) [cpp/gcc]
hw.cpp|14 col 9 error| note:   candidate expects 1 argument, 0 provided [cpp/gcc]
hw.cpp|36 col 9 error| no matching function for call to ‘Category::Category()’ [cpp/gcc]
hw.cpp|39 col 51 error| cannot call constructor ‘Category::Category’ directly [-fpermissive] [cpp/gcc]
hw.cpp|39 col 51 error| note: for a function-style cast, remove the redundant ‘::Category’ [cpp/gcc]

我的代码是:

class Category {
    private:
        string name;
    public:
        Category(string _name)
        {
            name = _name;
        }
        string getCategory()
        {
            return name;
        }
        void setCategory(string _name)
        {
            name = _name;
        }
};
class Book {
    private:
        string name;
        string author;
        Category category;
    public:
        Book(string _name, string _author, string _category)
        {
           name = _name;
           author = _author;
           category = Category::Category(_category);
        }
        Category getCategory()
        {
            return category;
        }
        void setCategory(string _name)
        {
            category.setCategory(_name);
        }
        string getName()
        {
            return name;
        }
        void setName(string _name)
        {
            name = _name;
        }
        string getAuthor()
        {
            return author;
        }
        void setAuthor(string _author)
        {
            author = _author;
        }
};

我的代码出了什么问题?我该如何解决它?

问题就在这里:

    Book(string _name, string _author, string _category)
    {
       name = _name;
       author = _author;
       category = Category::Category(_category);
    }

请看最后一行。您认为category在该行执行之前具有什么价值?您首先期望如何构建category,以便您可以在这里赋予它新的价值?

如何修复它取决于您要做什么。可以使用初始值设定项列表。可以使用默认构造函数。

相关内容

最新更新