在下面的程序中,是行
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;
}
答案 0 :(得分:5)
这是允许的,但它没有意义,因为编译器会为你打电话。不过,我恐怕今天早上不想做标准拖网。
答案 1 :(得分:0)
这是正确的,但不需要调用基类默认构造函数。 假设您使用的是g ++,您可能需要使用以下标志:-ansi(&lt; =&gt; -std = c ++ 98)