调用基类构造函数

4
在下面的程序中,这一行是:

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;
}

如果 OP 谈论 ANSI,则他很可能使用纯 C - abatishchev
4
这段话的意思是:@abatishchev,这段代码看起来像“纯C”吗?另外,C++也有一个ANSI标准。 - anon
@Neil Butterworth:你说得对,是我的疏忽。 - abatishchev
2个回答

5

虽然允许这样做,但这是没有意义的,因为编译器会自动调用。但很抱歉,我今天早上不想进行标准搜索。


0

这是正确的,但调用基类默认构造函数并不是必要的。 假设您正在使用g++,您可能希望使用以下标志:-ansi(<=> -std=c++98)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接