c++ - 调用基类构造函数

标签 c++ inheritance derived-class default-constructor

在下面的程序中,是行

Derived(double y): Base(), y_(y)

正确/允许?也就是说,它是否遵循 ANSI 规则?

#include <iostream>

class Base
{
 public:
  Base(): x_(0)
  {
   std::cout << "Base default constructor called" << std::endl;
  }
  Base(int x): x_(x)
  {
   std::cout << "Base constructor called with x = " << x << std::endl;
  }

  void display() const
  {
   std::cout << x_ << std::endl;
  }

 protected:
  int x_;      
};

class Derived: public Base
{
 public:
  Derived(): Base(1), y_(1.2)
  {
   std::cout << "Derived default constructor called" << std::endl;
  }
  Derived(double y): Base(), y_(y)
  {
   std::cout << "Derived constructor called with y = " << y << std::endl;
  }

  void display() const
  {
   std::cout << Base::x_ << ", " << y_ << std::endl;
  }

 private:
  double y_;      
};

int main()
{
 Base b1;
 b1.display();
 Derived d1;
 d1.display();
 std::cout << std::endl;
 Base b2(-9);
 b2.display();
 Derived d2(-8.7);
 d2.display();

 return 0;
}

最佳答案

这是允许的,但没有意义,因为编译器会为您进行调用。不过,恐怕我今天早上不想做标准拖网。

关于c++ - 调用基类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2707841/

相关文章:

java - List<T> 类型中的方法 add(T) 不适用于参数

c++ - 正确继承std::string的方法是什么?

C++:如何处理从 std:exception 派生的异常,具体取决于它们的类型?

具有默认参数的 C++ 基类构造函数

c++ - 代码不工作。使用堆栈

c++ - 高效解释串行数据

java - 继承 - 从 Employee 类创建 Commission Employee 类并进行测试

c++ - QSqlQueryModel 提示我的数据库没有打开

c++ - 我正在尝试传递一个 lambda 作为参数

c++ - C++ 中的 const 数组初始化,没有初始大小