C++程序输出16

预测下列C++程序的输出。

null

问题1

#include<iostream>
using namespace std;
class Base
{
public :
int fun()      { cout << "Base::fun() called" ; }
int fun( int i) { cout << "Base::fun(int i) called" ; }
};
class Derived: public Base
{
public :
int fun( char x)   { cout << "Derived::fun(char ) called" ; }
};
int main()
{
Derived d;
d.fun();
return 0;
}


输出:编译器错误。 在上面的程序中,基类的fun()在派生类中不可访问。如果派生类创建的成员方法的名称与基类中的一个方法相同,则所有具有此名称的基类方法都将隐藏在派生类中(请参见 更多细节)

问题2

#include<iostream>
using namespace std;
class Base
{
protected :
int x;
public :
Base ( int i){ x = i;}
};
class Derived : public Base
{
public :
Derived ( int i):x(i) { }
void print() { cout << x ; }
};
int main()
{
Derived d(10);
d.print();
}


输出:编译器错误 在上面的程序中,x是受保护的,因此可以在派生类中访问它。派生类构造函数试图使用 初始化列表 直接初始化x,这是不允许的,即使x是可访问的。基类的成员只能通过基类的构造函数调用进行初始化。下面是正确的程序。

#include<iostream>
using namespace std;
class Base {
protected :
int x;
public :
Base ( int i){ x = i;}
};
class Derived : public Base {
public :
Derived ( int i):Base(i) { }
void print() { cout << x; }
};
int main()
{
Derived d(10);
d.print();
}


输出:

 10 

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享