为什么下面的程序会出现错误 #include <iostream> using namespace std; class Base { public: virtual void print() const = 0; }; class DerivedOne : public Base { public: void print() const { cout << "DerivedOne\n"; } }; class DerivedTwo : public Base { public: void print() const { cout << "DerivedTwo\n"; } }; class Multiple : public DerivedOne, public DerivedTwo { public: void print() const { DerivedTwo :: print(); } }; int main() { int i; Multiple both; DerivedOne one; DerivedTwo two; Base *array[ 3 ]; array[ 0 ] = &both; array[ 1 ] = &one; array[ 2 ] = &two; array[ i ] -> print(); return 0; }
时间: 2024-01-14 08:04:06 浏览: 69
使用include <iostream>时一定要加using namespace std
这段代码会出现错误,因为在main函数中定义了一个整型变量i,并且没有对其进行初始化,导致在使用array[i] -> print()时,访问了未知的内存地址,产生了未定义的行为。
正确的做法应该是为变量i进行初始化,如下所示:
```
int main() {
int i = 0;
Multiple both;
DerivedOne one;
DerivedTwo two;
Base *array[3];
array[0] = &both;
array[1] = &one;
array[2] = &two;
array[i]->print();
return 0;
}
```
另外,由于类Multiple继承了两个基类DerivedOne和DerivedTwo,因此在使用时可能会产生二义性,需要使用作用域解析运算符来指定调用的是哪个基类的print函数,如Multiple::DerivedTwo::print()。
阅读全文