对于这个学校项目,我们需要一个包含 int 等级、char 颜色和两个 char* 到 C 风格字符串(用于操作和位置)的卡片类。我们需要包含以下内容的类:
1)卡片默认构造函数(默认等级和位置)
2)卡片参数化构造函数(所有数据成员作为参数)
3) 卡片复制构造函数
我不知道如何在类里面包含所有这些内容。我不断收到编译器错误,例如“候选人需要 _ 个参数,_ 给定”,候选人是:“然后列出我所有的构造函数。
我不知道如何在我的类中声明它们,如何在它们的实现中为它们命名,以及如何调用它们。
现在我有:
class card
{
public:
card(const int, const char*);
~card();
card(const card&);
card(const int, const char, const char*, const char*);
void copyCard(const card&);
void print();
void setColor(const char);
void setRank(const int);
void setAction(const char*);
void setLocation(const char*);
char getColor();
int getRank();
char* getAction();
char* getLocation();
private:
char color;
int rank;
char* action;
char* location;
};
我的构造函数:
card::card(const int newRank = -1, const char* newLocation = "location"){
color='c';
rank=newRank;
action = new char[7];
stringCopy(action, "action");
location = new char[9];
stringCopy(location, newLocation);
}
card::card(const card &newCard){
int length;
color = newCard.color;
rank = newCard.rank;
length = stringLength(newCard.action);
action = new char[length+1];
length = stringLength(newCard.location);
location= new char[length+1];
stringCopy(action, newCard.action);
stringCopy(location, newCard.location);
}
card::card(const int newRank, const char newCol, const char* newAct,
const char* newLoc){
int length;
color = newCol;
rank = newRank;
length = stringLength(newAct);
action = new char[length+1];
length = stringLength(newLoc);
location = new char[length+1];
stringCopy(action, newAct);
stringCopy(location, newLoc);
}
我在调用构造函数的地方遇到编译器错误(到目前为止):
card first;
和
miniDeck = new card[ 4 ];
我知道我需要告诉编译器哪个是哪个构造函数。但是如何呢?
最佳答案
问题是您实际上没有默认构造函数。一个类的默认构造函数是这样的,它没有传入任何参数,例如它有空参数列表,所以它的签名看起来像 card()
。
//编辑:
现在我看到您正试图在 card::card(const int newRank = -1, const char* newLocation = "location")
中设置默认参数值。但是,这是不正确的,您需要在 header 的方法声明中执行此操作,而不是在方法定义中执行此操作。那应该可以解决您的问题。
//编辑结束
只是为了给你一些好的提示,你可以遵循一些好的实践来改进你的代码(尽管这与你的代码的正确性无关):首先,找出关于 initialization list 的信息。以及它们的使用方式。其次 - 尽管这因程序员和项目而异 - 为您的类使用首字母大写(大驼峰式)的名称。
关于c++ - C++ 类中的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19556195/