[英]Static class member declaration error
我试图找到动态和静态实例化的对象编号。 我得到的错误,变量myheap未声明。
#include<iostream.h>
#include<stdlib.h>
class A {
public:
static int x; //To count number of total objects. incremented in constructor
static int myheap; //To count number of heap objects. Incremented in overloaded new
void* operator new(size_t t) {
A *p;
p=(A*)malloc(t);
myheap++;
return p;
}
void operator delete(void *p) {
free(p);
myheap--;
}
A() {
x++;
}
~A() {
x--;
}
};
int A::x=0;
int A::myheap=0;
int main() {
A *g,*h,*i;
A a,c,b,d,e;//Static allocations 5
g= new A();//Dynamic allocations 3
h= new A();
i= new A();
cout<<"Total"<<A::x<<'\n';
cout<<"Dynamic";
cout<<'\n'<<"HEAP"<<A::myheap;
delete g;
cout<<'\n'<<"After delete g"<<A::x;
cout<<'\n'<<"HEAP"<<A::myheap;
delete h;
cout<<'\n'<<"After delete h"<<A::x;
cout<<'\n'<<"HEAP"<<A::myheap;
delete i;
cout<<'\n'<<"After delete i"<<A::x;
cout<<'\n'<<"HEAP"<<A::myheap;
}
应该是A::myheap
。
同样,您的new操作符应该调用构造函数:
是的,您只需要将指针返回到新分配的对象即可。
void * operator new(size_t t)
{
A *p = (A*)malloc(t);
myheap++;
return p;
}
您没有本地命名myheap
但你有一个类范围的静态变量名为myheap
。 因此,您需要A::myheap
。 但实际上, myheap
和x
应该是私有的,并且应该定义静态的getx
和静态的getmyheap
公共方法。 而且,当然, x
应该有一个更好的名称。
您的代码几乎是正确的,但是您会看到有关“ myheap”的错误,因为编译器对早期错误感到困惑。 首先修复第一个错误。
关于重载运算符new,除了简单的malloc之外,还有更多其他功能。 我有一个先前的示例可能会有所帮助,但这是全局的,而不是特定于类的。
在此进行清理:(此命令可以编译并运行)
#include <iostream>
#include <memory>
#include <new>
#include <stdlib.h>
struct A {
static int count;
static int heap_count;
void* operator new(std::size_t t) {
void* p = malloc(t);
if (!p) throw std::bad_alloc();
heap_count++;
return p;
}
void operator delete(void *p) {
free(p);
heap_count--;
}
A() {
count++;
}
~A() {
count--;
}
};
int A::count = 0;
int A::heap_count = 0;
int main() {
using namespace std;
A a, b, c, d, e;
auto_ptr<A> g (new A), h (new A), i (new A);
cout << "Total: " << A::count << '\n';
cout << "Dynamic\nHeap: " << A::heap_count << '\n';
g.release();
cout << "After delete g: " << A::heap_count << '\n';
h.release();
cout << "After delete h: " << A::heap_count << '\n';
i.release();
cout << "After delete i: " << A::heap_count << '\n';
cout << "Heap: " << A::heap_count << '\n';
return 0;
}
桑迪普
当new不返回p时获得核心转储的原因是因为delete函数试图释放传入的指针。
由于new没有返回p,因此发送到delete()的值将为NULL或未初始化。 使用NULL指针或堆栈中的随机值调用free会导致程序崩溃。
最好,
山姆
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.