我今天去了一个面试,并得到了这个有趣的问题.
除了内存泄漏和事实上没有虚拟dtor,为什么这个代码会崩溃?
#include <iostream>
//besides the obvious mem leak, why does this code crash?
class Shape
{
public:
virtual void draw() const = 0;
};
class Circle : public Shape
{
public:
virtual void draw() const { }
int radius;
};
class Rectangle : public Shape
{
public:
virtual void draw() const { }
int height;
int width;
};
int main()
{
Shape * shapes = new Rectangle[10];
for (int i = 0; i < 10; ++i)
shapes[i].draw();
}
Run Code Online (Sandbox Code Playgroud) 考虑一对相关结构的以下声明.后代类不添加任何成员变量,唯一的成员函数是一个构造函数,它不会做任何事情,只是将其所有参数转发给基类的构造函数.
struct Base {
Base(int a, char const* b):
a(a), b(b)
{ }
int a;
char const* b;
};
struct Descendant: Base {
Descendant(int a, char const* b):
Base(a, b)
{ }
};
Run Code Online (Sandbox Code Playgroud)
现在考虑使用这些类型的以下代码.函数foo期望接收一个数组Base.但是,main定义一个数组Descendant并将其传递给它foo.
void foo(Base* array, unsigned len)
{
/* <access contents of array> */
}
int main()
{
Descendant main_array[] = {
Descendant(0, "zero"),
Descendant(1, "one")
};
foo(main_array, 2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
是否定义了该程序的行为?答案是否取决于它的主体foo,例如它是写入数组还是只读取它?
如果sizeof(Derived)不相等 …
我在C++中有以下代码:
#include <iostream>
class Number
{
public:
virtual void foo(){std::cout << "Number foo\n";};
Number (){ std::cout << "Number ctor" << std::endl;}
virtual ~Number(){ std::cout << "Number dtor" << std::endl;}
};
class Complex : public Number
{
public:
virtual void foo(){std::cout << "Complex foo\n";};
Complex (double r=0, double i=0) : _r (r), _i (i)
{ std::cout << "Complex ctor" << std::endl; };
virtual ~Complex(){ std::cout << "Complex dtor" << std::endl;}
private:
double _r,_i;
};
int main()
{
Number *numArr = new …Run Code Online (Sandbox Code Playgroud)