Why the following programs will couse error? a. Program 1 .cpp #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-14 07:02:58 浏览: 17
There are two errors in this program:
1. In class Parent, there is a redundant constructor `Parent(void)`. This will cause a compilation error, as there are multiple constructors with the same signature.
2. In class Parent, the destructor is defined as `Parent(void)` instead of `~Parent(void)`. This will cause a compilation error, as the class definition does not match the destructor declaration.
Here is the corrected program:
```cpp
#include <iostream>
using namespace std;
class Parent {
public:
Parent() {
cout << "Parent()\n";
}
Parent(int i) {
cout << "Parent(" << i << ")\n";
}
~Parent() {
cout << "~Parent()\n";
}
};
class Child1 : public Parent {};
class Child2 : public Parent {
public:
Child2() {
cout << "Child2()\n";
}
Child2(int i) : Parent(i) {
cout << "Child2(" << i << ")\n";
}
~Child2() {
cout << "~Child2()\n";
}
};
int main() {
Child1 a;
Child2 b;
Child2 c(42);
return 0;
}
```
This program should compile and run without errors.