逐行分析下列程序,并显示结果:#include <iostream.h> class BASE{ int m_base; public: BASE( int m_b=0 ) { m_base=m_b; cout<<"BASE Constructor! m_base="<<m_base<<endl; } virtual void f(){ cout<<"BASE::f() called!"<<endl; } virtual ~BASE(){ cout<<"BASE Destructor!"<<endl; } }; class DERIVE: public BASE{ int m_derive; public: DERIVE ( int a, int b=1 ):BASE(a) { m_derive=b; cout<<"DERIVE Constructor! m_derive="<<b<<endl; } void f( ) { cout<<"DERIVEL::f() called!"<<endl; } ~DERIVE() { cout<<"DERIVE Destructor!"<<endl; } }; void main() { BASE b[2]; b[0].f(); BASE *pb = new DERIVE(2,3); pb->f(); delete pb; }
时间: 2023-06-18 21:07:34 浏览: 53
这是一个 C++ 程序,包含两个类:BASE 和 DERIVE。
程序的主函数 main() 中定义了一个 BASE 类的数组 b,数组长度为 2,并依次调用了两个 BASE 类的构造函数 BASE()。然后调用了数组 b 的第一个元素的 f() 函数,输出 BASE::f() called!。
接下来,定义了一个指向基类 BASE 的指针 pb,并使用 new 运算符在堆上创建了一个 DERIVE 对象,构造函数 DERIVE() 中调用了基类 BASE 的构造函数 BASE(),并输出了 BASE Constructor! m_base=2 和 DERIVE Constructor! m_derive=3。
接着,通过指针 pb 调用了 DERIVE 类的 f() 函数,输出 DERIVEL::f() called!。
最后,使用 delete 运算符释放了 pb 所指向的内存,并在 DERIVE 类的析构函数 DERIVE::~DERIVE() 中输出了 DERIVE Destructor! 和 BASE Destructor!。
程序的输出结果如下:
BASE Constructor! m_base=0
BASE Constructor! m_base=0
BASE::f() called!
BASE Constructor! m_base=2
DERIVE Constructor! m_derive=3
DERIVEL::f() called!
DERIVE Destructor!
BASE Destructor!
BASE Destructor!
相关问题
执行下面的程序将输出( ) #include <iostream.h> class BASE{ char c; public: BASE(char n):c(n){} ~BASE(){cout<<c;} }; class DERIVED:public BASE{ char c; public: DERIVED(char n):BASE(n+1),c(n){} ~DERIVED(){cout<<c;} }; int main() { DERIVED(‘X’); return 0; } A XY B YX C X D Y
输出为 B YX。
在 main 函数中创建 DERIVED 对象时,调用 DERIVED 构造函数,该构造函数首先调用 BASE 构造函数并传递 'X'+1,然后初始化 DERIVED 类的成员变量 c 为 'X'。因此,首先输出的字符是 Y,然后是 X,最后是 DERIVED 对象的析构函数释放的字符 Y。因此,输出为 YX。
4. 修改以下程序,使其可以成功运行 #include<iostream.h> class base{ int x; public: void setx(int n){ x=n;} void showx( ){ cout<<x<<endl;} }; class derived:private base{ private: int y; public: void setxy(int n,int m) { setx(n); y=m; } void showxy( ){ cout<<x<<endl; cout<<y<<endl; } }; Int main() { derived obj; obj.setx(10); obj.showx(); obj.setxy(10,20); obj.showxy( ); return 0; }
修改后的程序如下:
```cpp
#include<iostream>
using namespace std;
class base{
int x;
public:
void setx(int n){ x=n;}
void showx( ){ cout<<x<<endl;}
};
class derived:private base{
int y;
public:
void setxy(int n,int m){ setx(n); y=m; }
void showxy( ){ cout<<base::x<<endl; cout<<y<<endl; }
};
int main() {
derived obj;
obj.setxy(10,20);
obj.showxy();
return 0;
}
```
在原程序中,由于类derived私有继承了类base,因此在main函数中不能访问base类的public成员函数setx和showx。解决方法是,将obj.setx(10);和obj.showx();改为obj.setxy(10,20);和obj.showxy();。同时,在showxy函数中,由于x是base类的private成员,不能直接访问,需要用base::x来访问。