呼叫基础类构造
问题描述:
在下面的程序中,是线呼叫基础类构造
正确/允许?那是否遵循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;
}
答
这是允许的,但它毫无意义,因为编译器会为您打电话。不过,恐怕我今天早上不想做标准拖网。
答
这是正确的,但调用基类的默认构造函数是没有必要的。 假设您使用的是g ++,您可能需要使用以下标志:-ansi(< => -std = C++ 98)
如果OP讨论的是ANSI,那么他使用纯C语言可能是 – abatishchev 2010-04-25 10:18:21
@abatishchev代码看起来像“纯C”一样吗?还有一个C++的ANSI标准。 – 2010-04-25 10:19:56
@尼尔·巴特沃斯:你说的对,我的疏忽。 – abatishchev 2010-04-25 20:52:22