我对大多数OO理论有了深刻的理解,但让我困惑的一件事是虚拟析构函数.
我认为无论什么以及链中的每个对象,析构函数总是会被调用.
你什么时候打算让它们成为虚拟的?为什么?
#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
virtual int area ()
{ return (0); }
};
class CRectangle: public CPolygon {
public:
int area () { return (width * height); }
};
Run Code Online (Sandbox Code Playgroud)
有汇编警告
Class '[C@1a9e0f7' has virtual method 'area' but non-virtual destructor
Run Code Online (Sandbox Code Playgroud)
如何理解这个警告以及如何改进代码?
[编辑]这个版本现在正确吗?(试图回答用这个概念来阐明自己)
#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
virtual ~CPolygon(){};
virtual int area ()
{ return (0); }
};
class CRectangle: public CPolygon {
public: …Run Code Online (Sandbox Code Playgroud) 我在我的代码中使用动态内存分配,并在尝试删除指向子类的指针时遇到问题.我发现当我使用delete关键字时,最初分配的内存不会被释放.该功能适用于原始基类.
这是一个问题,因为我在arduino上运行代码,RAM很快被吃掉然后崩溃.
这是一些示例代码:
class Base
{
public:
Base(){
objPtr = new SomeObject;
}
~Base(){
delete objPtr;
}
SomeObject* objPtr;
};
class Sub : public Base
{
public:
Sub(){
objPtr = new SomeObject;
}
};
// this works fine
int main()
{
for (int n=0;n<100;n++) // or any arbitrary number
{
Base* basePtr = new Base;
delete basePtr;
}
return 0;
}
// this crashes the arduino (runs out of RAM)
int main()
{
for (int n=0;n<100;n++) // or …Run Code Online (Sandbox Code Playgroud) 试图找到使用ptr_vector存储,访问和释放对象,尤其是当存储对象从其他遗传(ptr_vector不应该有对象切片的任何问题)的最佳方式.但是当运行下面的程序时,令人惊讶的是派生类没有被破坏.谁知道为什么?
#include <boost/ptr_container/ptr_vector.hpp>
#include <iostream>
#include <boost/ptr_container/ptr_map.hpp>
#include <boost/foreach.hpp>
using namespace std;
class A
{
public:
int id;
A() {cout<<"Constructed A()"<<endl;}
A(int i):id(i) {cout<<"Constructed A"<<i<<endl;}
~A() {cout<<"* Destructed A"<<id<<endl;}
};
class B:public A
{
public:
int i;
B() {cout<<"Constructed B"<<endl;}
B(int ii):i(ii) {id=ii;cout<<"Constructed B"<<i<<endl;}
~B() {cout<<"* Destructed B"<<i<<endl;}
};
class zoo
{
boost::ptr_vector<A> the_animals;
public:
void addAnimal(A* a) {the_animals.push_back( a );}
void removeAnimal(int id) {the_animals.release(the_animals.begin()+id); }
void removeOwnership(int id) {the_animals.release(the_animals.begin()+id).release();}
};
int main()
{
zoo z;
z.addAnimal( new B(0) ); …Run Code Online (Sandbox Code Playgroud)