首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >继承类C++

继承类C++
EN

Stack Overflow用户
提问于 2017-12-19 17:27:52
回答 1查看 76关注 0票数 5

我想像这样调用父构造函数:

代码语言:javascript
复制
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 )的默认构造函数

代码语言:javascript
复制
class Visual {
    private:
        Visual();
        Visual(const Visual &);
    protected:
        Position coordinate;
        char chara;
    public:
        Visual(char c, int x, int y);
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-19 17:31:39

创建一个函数,将方向转换为不同的字符,并将其传递给公共构造函数:

代码语言:javascript
复制
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) 
{
}
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47892273

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档