c++ - C++中的向上转型和向下转型

标签 c++ dynamic-cast downcast upcasting

我正在尝试使用 Visual Studio C++ 2010 Express 和 dynamic_cast 在 C++ 中进行转换的想法。 但不知何故,当我运行它时,猫对象实际上可以执行狗的行为。

似乎 Dog d = (Dog)aa; 让编译器感到困惑。有什么建议吗?

下面是我的代码。

`
#include <iostream>
#include <string>

using namespace std;

class Animal {
public:
    string name ;
    Animal(string n) : name(n) {cout << "construct animal " << name << endl ;  }
    Animal() : name("none") { };
    virtual string getName() { return name ; }
    virtual ~Animal() { cout << "destruct animal " << name << endl ; }
};

class Dog: public Animal{

public:
    Dog() :Animal("") { }
    Dog(string n): Animal(n) {
        cout << "construct Dog" << endl ; 
    }
    void dogStuff() { cout << "hello woof...."; }
};

class Cat: public Animal{

public:
    Cat() :Animal("") { }
    Cat(string n): Animal(n) {
        cout << "construct Cat" << endl ; 
    }
    void catStuff() { cout << "hello meow...."; }
};

int main() { 

    Animal *aa = new Cat("Catty"); // cat upcasting to animal 
    Dog *d = (Dog*)aa; // animal downcasting to dog. ???
    cout << d->getName() << endl;
    d->dogStuff();
    Dog* dog = dynamic_cast<Dog*>(d) ;

    if(dog)  { 
        cout << "valid  cast" << endl ;
        dog->dogStuff();
        cout << dog->getName();
    }else
        cout << "invalid  cast" << endl ;

    int i ;
    cin >> i ;

    return 0;
}

输出

构建动物Catty

构造猫

一斤

你好哇....有效类型转换

你好哇....猫

`

最佳答案

Dog *d = (Dog*)aa;

类型转换的括号样式称为 C-style cast ,因为它旨在模仿 C 的行为。在这种情况下,编译器执行 static_cast,继续将 Animal* 向下转换为 Dog*,基于假设底层对象是Dog。因为底层对象实际上是 Cat,所以程序格式错误,任何事情都可能发生,包括内存损坏。 C 风格的转换从不进行任何运行时安全检查。

Dog* dog = dynamic_cast<Dog*>(d);

此转换实际上不需要执行任何操作:它正在从 Dog* 转换为 Dog*。不必执行运行时安全检查,即使使用了 dynamic_cast,因为 d 被假定为格式正确的 Dog*

建议

避免 C 风格的转换。确保任何向下转型都是有效的。我个人不太使用 dynamic_cast,但我有责任只正确地向下转换。

关于c++ - C++中的向上转型和向下转型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50033789/

相关文章:

c++ - ‘<’ 标记之前预期的构造函数、析构函数或类型转换

c# - 找到二维数组中的对角线

运行时没有.dll文件的c++ HTTP请求

c++ - opencv cv::Ptr 的动态转换

c++ - 这是对 dynamic_cast 的正确使用吗?

c++ - 自动向下转换指向派生对象的指针

C++ 脏字符 *

c++ - dynamic_cast 和右值引用

java 将对象用作 double 而无需显式强制转换

c++ - 是否有任何 C++ 工具可以检测 static_cast、dynamic_cast 和 reinterpret_cast 的滥用?