小编use*_*113的帖子

虚函数

class a
{
 virtual void foo(void) ;
};

class b : public  a
{
public:
 virtual void foo(void)
  {
  cout<< "class b";
  }
};

int main ( ) 
{
class a *b_ptr = new b ;
b_ptr->foo();
}
Run Code Online (Sandbox Code Playgroud)

请指导我为什么b_ptr-> foo()不会调用类b的foo()函数?

c++

7
推荐指数
2
解决办法
416
查看次数

资源获取是初始化"RAII"

在下面的例子中

class X
{
    int *r;
public: 
    X() {
        cout << "X is created";
        r = new int[10];
    };
    ~X() {
        cout<< "X is destroyed";
        delete [] r;
    };
};
class Y
{
public: 
    Y() {
        X x;
        throw 44;
    }; 
    ~Y() {
        cout << "Y is destroyed";
    };
};
Run Code Online (Sandbox Code Playgroud)

我从一个站点得到了RAII的这个例子并且有些疑惑.请帮忙.

  1. 在x的构造函数中,我们没有考虑"如果内存分配失败"的情况.
  2. 这里对于Y的析构函数是安全的,因为在y construcotr中没有分配任何内存.如果我们还需要在y构造函数中做一些内存分配怎么办?

c++ raii

1
推荐指数
2
解决办法
507
查看次数

标签 统计

c++ ×2

raii ×1