如果这低于社区的工资等级,我们深表歉意。我昨晚才开始学习OOP和课程,英语不是我的母语。
我正试图创建一个名为";哺乳动物";将其名称、毛发类型、腿数和尾巴的存在作为属性。这就是我的哺乳动物h的样子。
//mammal.h
#include <string>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Mammal
{
public:
//Properties
enum Fur {bald, curly, frizzy, matted, shorthair, longhair, fluffy};
Fur flooftype;
int Legs;
bool Tail;
string Name;
//Methods
Mammal(string Name, Fur flooftype, int Legs, bool Tail);
void identifyMammal(string Name, Fur flooftype, int Legs, bool Tail)
{
cout<<"Name: " << Name << endl;
cout<<"Number of legs: "<< Legs << endl;
cout<<"Fur type: "<< flooftype << endl;
if(Tail==true){
cout<<"This mammal has a tail.";
}else{
cout<<"This mammal has no tail.";
}
}
};
Mammal::Mammal(string Name, Fur flooftype, int Legs, bool Tail)
{
Name=Name;
flooftype=flooftype;
Legs=Legs;
Tail=Tail;
}
这是我的主.cpp:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include "mammal.h"
using namespace std;
int main()
{
Mammal cat1;
cout << Mammal.identifyMammal() << "." <<endl;
cout << endl;
system ("pause");
return EXIT_SUCCESS;
}
我无法编译此代码,它给了我以下错误:
no default constructor exists for class "Mammal"
type name is not allowed
我不知道为什么它不认可我的构造函数。有人能给我指正确的方向吗?
您已经编写了一个构造函数,但您的构造函数不是默认的构造函数。它采用参数name
、flooftype
、Legs
和Tail
。要使用该构造函数初始化Mammal
,您需要编写一个类似的调用
Mammal cat1("Captain", shorthair, 4, true);
C++将自动为您的类提供默认构造函数(请参阅此处的隐式声明和定义的默认构造函数部分(,但仅当您不编写自己的构造函数时。因为您编写了一个非默认构造函数,所以您不再获得隐式声明的默认构造函数,因此您的类根本没有默认构造函数。这意味着真正需要转到默认构造函数的调用
Mammal cat1;
是一个编译时错误。
行Mammal cat1;
需要一个默认构造函数,因为您没有向它传递参数。请编写一个默认的构造函数,或者为您编写的四参数构造函数传递值。
Mammal cat1;
这行调用默认构造函数,但是您没有它,因为:
Mammal::Mammal(string Name, Fur flooftype, int Legs, bool Tail)
更改为Mammal cat1("name", matted, 2, true)
或添加Mammal() = default
您的构造函数是Mammal(string Name, Fur flooftype, int Legs, bool Tail);
但您正在尝试调用Mammal()
构造函数。
这里有一个很好的解释。