c++ - 我可以在 C++11 的类外执行继承吗?

标签 c++ oop templates inheritance c++11

假设我想用不同的指针类型在我的类之外重载一个函数。我可以在 C++11 中执行此操作吗?

struct Bird;
struct Bear;

struct Animal {
    virtual Bird* AsBird() = 0;
    virtual Bear* AsBear() = 0;
};
struct Bird : public Animal{
    virtual Bird* AsBird(){ return this; }
    virtual Bear* AsBear(){ return NULL; }
};
struct Bear : public Animal{
    virtual Bird* AsBird(){ return NULL; }
    virtual Bear* AsBear(){ return this; }
};

void Print(Animal* a){
    cout << "I don't know what animal this is!" << endl;
}

void Print(Bear* b){
    cout << "That's a bear!" << endl;
}

void Print(Bird* b){
    cout << "That's a bird!" << endl;
}

int main(int argc, char* argv[]){

    Animal* a = new Bear;

    Bear* bear;
    Bird* bird;

    if (bear = a->AsBear()){
        Print(bear);
    } else if (bird = a->AsBird()){
        Print(bird);
    }

    return 0;
}

此代码有效,但绝对糟糕。我试过使用模板和自动,但编译器不想与我的邪恶实验有任何关系。有这样做的合法方法吗?

最佳答案

您所做的是重载 Print通过更改其参数类型的自由函数,不涉及继承,这是完全合法的。

但是您不需要它(或任何类似 dynamic_cast 的东西):您应该做的是添加一个 virtual void Print() const = 0在你的Animal而不是基类,并在每个派生类中覆盖它。

示例:

struct Animal {
    virtual void Print() const = 0;
};

struct Bird : public Animal{
    void Print() const { cout << "That's a bird!\n"; }
};

struct Bear : public Animal{
    void Print() const { cout << "That's a bear!\n"; }
};

int main(){

    Animal* a = new Bear;
    a->Print();

    Animal* b = new Bird;
    b->Print();
}

关于c++ - 我可以在 C++11 的类外执行继承吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25399067/

相关文章:

c++ - 关于使用 native Visual C++ 项目与 makefile 项目的意见

c++ - std::lower_bound 中没有小情况吗?

java - 使用 JNDI 在 Tomcat 中共享 servlet session 对象和数据

c++ - 模板类型是否浪费 C++ 中的空间?

c++ - gcc 编译带有大量模板参数的模板类时出错

c++ - 当我尝试使用异常时,为什么我的代码在 Qt Creator 中使用 -fno-exceptions 进行编译?

c++ - for循环跳过getline

php - Laravel:从公共(public)静态函数访问类变量(基本的 oop 问题)

javascript 不是构造函数

c++ - 是否有任何常规模式可以确定将...放在模板中的位置?