c++ - 继承类 C++

标签 c++ inheritance

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

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/

相关文章:

C++ - 在输出文件中打印不需要的字符

c++ - 使用类型= smth。和模板化类型

php - 优化 MySQL 查询以获得正确的页面模板

java - 如何为一个方法定义多个实现?

c++ - 为什么我不能将父类(super class)引用强制转换为也扩展另一个父类(super class)的子类?

objective-c - 父类(super class)中的静态变量

c++ - 渲染多个对象的 OpenGL 问题

c++ - 设置区域设置后输入 4 位数字时,operator>> 返回失败

c++ - 应该在策略模式中使用安全指针吗?

c# - 私有(private)成员是否在 C# 中继承?