-2

我看过类似的查询,但我似乎让自己迷失了方向。我有一个简单的例子,所以请考虑以下几点:

#include <iostream>
using namespace std;

class Animal
{
  public:
    Animal() {cout << "Animal" << endl;}
};

class Cat : public Animal
{
  public:
    Cat() {cout << "Cat" << endl;};
};

int main()
{
  Cat c;
  return 0;
}

程序运行时会显示

Animal
Cat

我现在的问题是:实际上首先调用了哪个构造函数。在执行其内容之前是否调用了 Cat(),然后 Cat() 调用了 Animal(),或者编译器/程序是否查看 Cat(),看到它是一个 Animal(),然后先调用 Animal(),然后调用 Cat()?

4

3 回答 3

4

在调用 Cat 构造函数时,作为 Cat 对象初始化的一部分,Animal 构造函数在 Cat 构造函数主体之前执行。就像您在初始化列表中显式执行此操作一样:

Cat () : Animal() {
     cout << "Cat" << endl;
}

如果要将参数传递给基类构造函数,则必须如上所述显式执行,否则会为您调用默认构造函数(没有参数的构造函数)。在任何一种情况下,基类构造函数都会在派生对象的初始化继续之前完成。

于 2013-08-28T18:45:10.760 回答
1

When the Cat constructor is called, two things happens, first the initialization list is executed and then the construction function. Implicitly you are doing this:

class Cat : public Animal
{
  public:
    Cat() 
    : Animal()
    {
        cout << "Cat" << endl;
    };
};

Then the Animal constructor is executed before the Cat implementation of the Cat constructor, but after it initialization list. For example, if the Cat and Animal classes have some members and you want to initialize them in the constructor, you could see this more easily:

class Animal
{
  private:
    bool haveHair;
  public:
    Animal(bool hair)
    :    haveHair(hair)
    {
        cout << "Animal" << endl;
    }
};

class Cat : public Animal
{
  public:
    Cat() 
    : Animal(true)
    {
        cout << "Cat" << endl;
    }
};
于 2013-08-28T18:51:42.883 回答
0

首先调用 Animal(),然后调用 Cat()。

首先 Animal 类分配内存,然后是 Cat。也许您想在 Cat 构造函数中从 Animal 访问资源。

于 2013-08-28T18:45:36.017 回答