c++ - 这个指针构造函数是如何定义的?

标签 c++ pointers constructor

我不明白下面的 Animal(Animal*) 构造函数是如何定义的。代码编译并正确运行。

class Animal {
public:
    virtual ~Animal() {}
    virtual std::string specie() = 0;
    virtual std::string family() = 0;
};

class Rodent : public Animal {
public:
    std::string family() override { return "rodent"; }
};

class Rabbit : public Rodent {
public:
    std::string specie() override { return "rabbit"; }
};

int main() {
    Animal* goffy(new Rabbit());
}

new Rabbit() 返回 Rabbit*,它继承了 Animal*,所以构造函数采用指向自身的指针?

最佳答案

您正在执行 direct initialisation .

表达式new Rabbit()会返回 Rabbit* .这Rabbit*然后将值转换为 Animal*值,这是可能的,因为 AnimalRabbit 的基类. Animal*然后将值分配给 goffy变量。

关于c++ - 这个指针构造函数是如何定义的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43751222/

相关文章:

c++ - C 数组 vs 指针 : array is considered as a variable, array+0 被认为是指针?

java - Java 中带有 <> 的特殊构造函数

c++ - 类是否具有自反性? (即实例总是等于它们自己吗?)

c++ - 在 multiset 中维护一个排序的数字列表,在另一个中维护累积和

c++ - 如何将变量的元素转换为 std::string ( c++ )

iphone - 从 NSDictionary 设置 CGRect.frame.size 的值

c - 请求非结构或 union 中的成员 xxxx

c++ - C++中的类存储保证

c++ - 构造函数中的段错误

java - Dagger 2 注入(inject)构造函数