【发布时间】:2019-11-29 20:43:43
【问题描述】:
以下代码编译但运行时出现分段错误。我使用的是动态内存 主要使用指向派生类对象的基类指针,并且在运行时会出错。
#include <iostream>
using namespace std;
class Base {
public:
int b;
int b1;
Base() : b(0), b1(0) { cout << "Base constructor" << endl; }
virtual void Input() {
cout << "Enter number b : ";
cin >> b >> b1;
// return *this;
}
virtual ~Base() {}
};
class Derived : public Base {
public:
int d;
// Constructor
Derived() : d(0) { cout << "Derived constructor" << endl; }
void Input() {
Base::Input();
cout << "Enter number d : ";
cin >> d; //>> d1;
// return *this;
}
~Derived() {}
};
int main() {
Base *s = new Derived[2];
// When complexity of data members increases this line causes
// segmentation fault
s[1].Input(); // Here the problem
delete[] s;
}
【问题讨论】:
-
您能否礼貌地显示错误发生的位置?
-
Base *s = new Derived[2]。危险威尔罗宾逊! -
您不能创建 Derived 数组并使用 Base 指针访问该数组。
-
如果你想要一个指针数组,你应该使用
new两次。 -
仅仅因为编译的东西不意味着它是一个有效的 C++ 程序。
标签: c++