簡體   English   中英

靜態類成員聲明錯誤

[英]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 但實際上, myheapx應該是私有的,並且應該定義靜態的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM