我想这样调用父构造函数:
Character::Character(int x, int y, int h, int s, int a, char dir) : health(h), strength(s), armor(a), direction(dir){
if(direction == 'N') {
Visual('^', x, y);
} else if(direction == 'S') {
Visual('v', x, y);
} else if(direction == 'W') {
Visual('<', x, y);
} else if(direction == 'E') {
Visual('>', x, y);
}
}
但它不能很好地工作,因为它调用了父级的默认构造函数,该构造函数是 private
class Visual {
private:
Visual();
Visual(const Visual &);
protected:
Position coordinate;
char chara;
public:
Visual(char c, int x, int y);
};
最佳答案
创建一个函数将方向转换为不同的字符,并将其传递给公共(public)构造函数:
namespace { //Anonymous Namespace for functions local to your .cpp files to avoid definition conflicts
char convert_direction(char c) {
switch(c) {
case 'N': return '^';
case 'S': return 'v';
case 'E': return '>';
case 'W': return '<';
default: return '?';
}
}
}
Character::Character(int x, int y, int h, int s, int a, char dir) :
Visual(convert_direction(dir), x, y),
health(h), strength(s), armor(a), direction(dir)
{
}
关于c++ - 继承类 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47892273/