调用基类构造函数
在下面的程序中,该行是否
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;
}
In the program below, is the line
Derived(double y): Base(), y_(y)
correct/allowed? That is, does it follow ANSI rules?
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是允许的,但毫无意义,因为编译器会为您进行调用。不过,恐怕今天早上我不想进行标准拖网捕鱼。
It's allowed, but it's pointless, as the compiler will make the call for you. I'm afraid I don't feel like doing a Standard trawl this morning, though.
这是正确的,但不需要调用基类默认构造函数。
假设您使用的是 g++,您可能需要使用以下标志:-ansi (<=> -std=c++98)
This is correct but calls to the base class default constructors are not necessary.
Assuming you are using g++, you may want to use the following flag: -ansi (<=> -std=c++98)