我試着編寫一個代碼來創建一個類,它的對象只能在堆上創建,但不能在堆棧上創建。但在編譯期間,我得到了一些鏈接錯誤。錯誤創建一個類的對象不能在堆棧上創建,但只能在堆上創建?
# include<iostream>
# include<stdio.h>
# include<conio.h>
using namespace std;
class Rect
{
int length;
int breadth;
Rect();
public :
Rect & operator = (const Rect&);
Rect(const Rect& abc)
{
cout<<"in copy const"<<"\n";
}
~Rect();
int area_rect()
{
return length*breadth;
}
void set_value(int a,int b);
static Rect* instance()
{
Rect* ptr=NULL;
ptr=new Rect ;
return ptr;
}
};
void Rect::set_value(int a,int b)
{
length=a;
breadth=b;
}
int main()
{
Rect* a= Rect::instance();
a->set_value(10,3);
cout << "area realted to object a : " << a->area_rect() <<"\n";
Rect* b=a;
b->set_value(10,4);
cout << "area realted to object a : " << a->area_rect() <<"\n";
cout << "area realted to object b : " << b->area_rect() <<"\n";
delete b;
getch();
return 0;
}
我得到了以下錯誤:
ccUfbaaa.o(.text+0x24f) In function `main': [Linker error] undefined reference to `Rect::~Rect()'
ccUfbaaa.o(.text$_ZN4Rect8instanceEv[Rect::instance()]+0x60) In function `ZN4Rect9area_rectEv': [Linker error] undefined reference to `Rect::Rect()'
ccUfbaaa.o(.text$_ZN4Rect8instanceEv[Rect::instance()]+0x60) ld returned 1 exit status .
我知道我可以讓析構函數私有,將只允許在堆被裝箱的對象。但在那種情況下,我怎樣才能刪除創建的對象?我們如何糾正這個錯誤?
您沒有〜Rect()的實現,並且您沒有默認構造函數... – 2012-02-07 20:24:56