保存时,我的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;
}
};
我的代码有什么问题?我该如何解决?
答案 0 :(得分:2)
问题在于:
Book(string _name, string _author, string _category)
{
name = _name;
author = _author;
category = Category::Category(_category);
}
看最后一行。在该行执行之前,您认为category
有什么价值?您如何期望首先构建category
以便在此处为其提供新值?
如何修复它取决于您想要做什么。您可以使用初始化列表。您可以使用默认构造函数。