如下程序的输出结果是( )。 #include<iostream> using namespace std; class B { public: virtual void f() { cout<<"B"; } void g(){ cout<<"B"; } }; class D:public B { public: void f(){ cout<<"D"; } void g(){ cout<<"D"; } }; void h(B*p) { p->f(); p->g(); } int main() { D obj; h(&obj); return 0; }
时间: 2024-02-14 14:20:40 浏览: 25
程序的输出结果是:D B。
解析如下:
- 在 main 函数中,创建了一个 D 类型的对象 obj,然后调用 h 函数,将 obj 的地址传递给 h 函数。
- 在 h 函数中,通过指针 p 调用了两个函数:f 和 g。
- 因为 f 函数是虚函数,在类 B 中被声明为虚函数,因此在类 D 中被重写。因此,p->f() 调用的是 D 类中重写后的 f 函数,输出 D。
- g 函数不是虚函数,因此 p->g() 调用的是类 B 中的 g 函数,输出 B。
相关问题
分析下列程序,根据输出结果完善填空。 程序运行结果为:10 20 30 #include <iostream > using namespace std; class A {
由于题目中给出的程序不完整,我在此做出一些假设来完善程序。假设程序如下:
```c++
#include <iostream>
using namespace std;
class A {
public:
A(int x) {
a = x;
}
virtual void f() {
cout << a << " ";
}
private:
int a;
};
class B : public A {
public:
B(int x, int y) : A(x) {
b = y;
}
void f() {
cout << b << " ";
}
private:
int b;
};
int main() {
A *p = new B(10, 20);
p->f();
delete p;
A a(30);
a.f();
return 0;
}
```
程序中定义了两个类 A 和 B,其中 B 继承自 A。类 A 中有一个 int 类型的成员变量 a 和一个虚函数 f(),该函数输出 a 的值。类 B 中有一个 int 类型的成员变量 b,并重写了类 A 中的虚函数 f(),该函数输出 b 的值。
在主函数中,首先定义了一个指向类 B 对象的指针 p,并调用 p 的 f() 函数输出 b 的值,然后使用 delete 操作符释放该对象的内存。接着定义了一个类 A 的对象 a,并调用 a 的 f() 函数输出 a 的值。最终程序输出了
```
20 30
```
的结果。
具体分析如下:
首先定义了指向类 B 对象的指针 p,该对象的成员变量 a 被初始化为 10,b 被初始化为 20。由于类 A 中的 f() 函数是虚函数,因此在调用 p 的 f() 函数时,会动态绑定到类 B 中的 f() 函数,输出 b 的值 20。
接着使用 delete 操作符释放指针 p 所指向的对象的内存。
然后定义了一个类 A 的对象 a,该对象的成员变量 a 被初始化为 30。调用 a 的 f() 函数时,由于 a 是类 A 的对象,因此会调用类 A 中的 f() 函数,输出 a 的值 30。
因此最终程序输出了 20 和 30 两个数,中间以空格隔开。
#include<iostream> using namespace std; #include<iostream> using namespace std; //在此处添加代码 class Line: public Shape{ public: void Show(){cout<<"Line"<<endl;} }; class Rect: public Shape{ public: void show(){cout<<"Rect"<<endl;} }; int main(){ Shape *p = new Line(); p->Show(); delete p; Shape *p = new Rect(); p->Show(); delete p; return 0; } 输出结果: Line Rect
这段代码存在问题,因为在 main 函数中定义了两个名为 p 的指针变量,这样会导致编译错误。
另外,类 Rect 中的 show 函数名应该改为 Show,以保持与基类 Shape 中的虚函数名一致。修改后的代码如下:
```
#include<iostream>
using namespace std;
class Shape{
public:
virtual void Show() = 0;
};
class Line: public Shape{
public:
void Show(){ cout << "Line" << endl; }
};
class Rect: public Shape{
public:
void Show(){ cout << "Rect" << endl; }
};
int main(){
Shape *p = new Line();
p->Show();
delete p;
p = new Rect();
p->Show();
delete p;
return 0;
}
```
输出结果为:
```
Line
Rect
```
其中,Shape 类中的 Show 函数是纯虚函数,因此 Line 和 Rect 类都需要实现该函数并重写基类中的该函数。在 main 函数中,先创建一个指向 Line 类对象的 Shape 指针 p,调用 p 的 Show 函数输出 "Line",然后释放内存;再创建一个指向 Rect 类对象的 Shape 指针 p,调用 p 的 Show 函数输出 "Rect",最后再释放内存。