调用超类构造函数或方法的最佳方法是?

时间:2015-02-12 08:55:00

标签: c++ constructor superclass

我需要明确,明确调用超类构造函数/方法的最佳方法。

我尝试使用以下两种方式来调用超类构造函数:

Myclass::Myclass(int a, int b):X(a),Y(b)
{
    // do something
}

Myclass::Myclass(int a, int b)
{
X = a;
Y = b;
}

所以我在这里的问题是:

  1. 哪个是明确调用超类构造函数/方法的最佳方法?
  2. 这两种方式都会带来什么好处?
  3. 最佳做法是什么?为什么?
  4. 两种方式都存在任何性能问题?
  5. 关于我的问题,我找到了这个链接: What are the rules for calling the superclass constructor?但我仍然不再怀疑上面提到的问题。

    如果有任何在线教程,博客或视频也可以在这里提及,那对我来说将是非常有用的。提前谢谢.....

1 个答案:

答案 0 :(得分:4)

调用超类的构造函数的唯一正确方法是从初始化列表:

Myclass::Myclass(int a, int b)
    :X(a),Y(b)
{}

另一种方式实际上调用了不同的构造函数:

Myclass::Myclass(int a, int b)
    // implicit :X(),Y()
{
    // These two don't call constructors but actually declare variables
    X(a);
    Y(b);
}
相关问题