我想像这样调用父构造函数: 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'
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); } }
但它不能很好地工作,因为它调用私有的父默认构造函数
class Visual { private: Visual(); Visual(const Visual &); protected: Position coordinate; char chara; public: Visual(char c, int x, int y); };创建一个函数将方向转换为另一个字符,并将其传递给公共构造函数:
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) { }