#include <iostream> using namespace std; class A{ public: { cout<<"A::f()\n"; } }; class B:public A{ public: void f() {cout<<"B::f()\n"; } }; int main() { B b; A &p ; f(); return 0; }
时间: 2024-03-09 19:48:15 浏览: 31
这段代码存在一些问题。首先,类A中的函数f没有函数名,应该加上函数名。其次,在B类中重写了函数f,但是在main函数中调用的是A类中的函数f,应该改为调用B类中的函数f。此外,A类中的构造函数应该加上函数名和参数列表。修改后的代码如下:
```
#include <iostream>
using namespace std;
class A{
public:
A(){
cout<<"A::A()\n";
}
void f(){
cout<<"A::f()\n";
}
};
class B:public A{
public:
void f(){
cout<<"B::f()\n";
}
};
int main(){
B b;
A &p = b;
p.f();
return 0;
}
```
输出结果为:
```
A::A()
B::f()
```
相关问题
补全程序,并写出程序运行结果。 #include <iostream> using namespace std; class Class { public : Class ( int...
补全程序如下:
```
#include <iostream>
using namespace std;
class Class {
public:
Class(int num) {
cout << "Constructor with one argument called." << endl;
}
Class(int num1, int num2) {
cout << "Constructor with two arguments called." << endl;
}
};
int main() {
Class obj1(10);
Class obj2(20, 30);
return 0;
}
```
程序运行结果为:
```
Constructor with one argument called.
Constructor with two arguments called.
```
解释:
这是一个带有两个构造函数的类`Class`。第一个构造函数接受一个整数参数,第二个构造函数接受两个整数参数。在`main`函数中,我们创建了两个对象`obj1`和`obj2`,分别调用了两个不同的构造函数。所以,程序输出了两个不同的消息。
分析下列程序,根据输出结果完善填空。 程序运行结果为: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 两个数,中间以空格隔开。