为什么以下程序会出错? #include <iostream> using namespace std; class Parent { public: Parent (void) { cout << "Parent()\n"; } Parent (int i) { cout << "Parent("<< i << ")\n"; }; Parent (void) { cout << "~Parent()\n"; }; }; class Child1 : public Parent { }; class Child2 : public Parent { public: Child2 (void) { cout << "Child2()\n"; } Child2 (int i) : Parent (i) { cout << "Child2(" << i << ")\n"; } ~Child2 (void) { cout << "~Child2()\n"; } }; int main (void) { Child1 a; Child2 b; Child2 c(42); return 0; }
时间: 2024-01-18 08:03:09 浏览: 21
这段程序会出错,因为在 `Parent` 类中定义了两个同名的默认构造函数,导致编译器不知道该使用哪个构造函数来实例化对象。
具体来说,`Parent` 类中定义了两个无参构造函数:
```
Parent (void)
{
cout << "Parent()\n";
}
Parent (void)
{
cout << "~Parent()\n";
};
```
这两个构造函数在语法上都是合法的,但是它们的函数体是相互矛盾的,一个是构造函数的函数体,一个是析构函数的函数体。因此,编译器无法确定应该使用哪个构造函数来实例化 `Parent` 类的对象。
要解决这个问题,需要将 `Parent` 类的构造函数和析构函数正确地定义为一对匹配的构造函数和析构函数,例如:
```
Parent(void) {
cout << "Parent()\n";
}
Parent(int i) {
cout << "Parent(" << i << ")\n";
}
~Parent(void) {
cout << "~Parent()\n";
};
```
这样就可以正确地实例化 `Parent` 类的对象,并且可以顺利地执行程序。
相关问题
1.#include<iostream> using namespace std; class Parent [] public: virtual void f() [ cout<<"invoke f from Parent"<<endl; 了 }; class Child:public Parent [ public:void f() { cout <<"invoke f from Child"<<endl; 了 }; void p(Parent &a) [ a. f(); } int main() [[] Parent a; p(a); Child b; b. f( ); p(b); return 0; 了
这段代码存在语法错误,需要进行修正,具体修改如下:
```
#include <iostream>
using namespace std;
class Parent {
public:
virtual void f() {
cout << "invoke f from Parent" << endl;
}
};
class Child : public Parent {
public:
void f() {
cout << "invoke f from Child" << endl;
}
};
void p(Parent& a) {
a.f();
}
int main() {
Parent a;
p(a);
Child b;
b.f();
p(b);
return 0;
}
```
这段代码定义了一个父类 `Parent` 和一个继承自父类的子类 `Child`,并且在 `Parent` 类中定义了一个虚函数 `f()`。在 `p()` 函数中,以 `Parent` 类型的引用作为参数,调用了 `a.f()`,在 `main()` 函数中,实例化了 `Parent` 对象 `a` 和 `Child` 对象 `b`,并分别调用了它们的 `f()` 函数,观察输出结果可以看到虚函数的多态性,即 `p()` 函数调用时,根据实参的实际类型调用了不同的函数。
#include <iostream> using namespace std; class Parent { public: virtual void f() { cout << "invoke f from Parent" << endl; } }; class Child : public Parent { public: void f() { cout << "invoke f from Child" << endl; } }; void p(Parent& a) { a.f(); } int main() { Parent a; p(a); Child b; b.f(); p(b); return 0; }输出结果是什么
输出结果为:
```
invoke f from Parent
invoke f from Child
invoke f from Child
```
首先定义了一个`Parent`类和一个`Child`类,`Child`类继承自`Parent`类并重写了`f()`方法。
然后定义了一个函数`p()`,参数为`Parent`的引用,函数中调用了`a.f()`方法。
在`main()`函数中,先创建了一个`Parent`类对象`a`,调用`p(a)`方法,输出`invoke f from Parent`。
然后创建了一个`Child`类对象`b`,调用`b.f()`方法,输出`invoke f from Child`。
最后再次调用`p(b)`方法,由于参数是`Parent`类型的引用,而`b`是`Child`类型的对象,因此会调用`Parent`类中的`f()`方法,输出`invoke f from Child`。这就是多态性的表现。