簡體   English   中英

C ++指針和類

[英]C++ pointers and classes

嘗試在最后45分鍾解決這個問題,但無法弄清楚我想要做什么。 這是問題所在。

class C; //forward declaration
class Cpointer {
 public:

};

class C { //do not modify
   int i;
  public:
   C(int _i=0) : i(_i) {}
   Cpointer operator& () { return Cpointer(this); }
   void Do() { std::cout << "i=" << i << std::endl; }
 };


 int main() {
   Cpointer p (new C(100));
   p->Do();
 }

完成類Cpointer以便代碼編譯。 確保沒有內存泄漏。

據我所知,CPointer類將C類作為構造函數的參數。 當我嘗試下面的代碼時,我得到一個編譯器錯誤,告訴CPointer的Do函數中“使用未定義的類型C”。

class Cpointer
{
 C* mCptr;
   public:
  Cpointer(C* cptr) : mCptr(cptr){}
  void Do()
  {
    //mCptr->Do();
  }
};

我覺得稍微不安的發布解決方案,但因為你說這不是一個功課......這里是:

class Cpointer {
    C* ptr;
    public:
        Cpointer(C* c) : ptr(c) { }
        ~Cpointer() { delete ptr; }
        C* operator->() { return ptr; }
};

這里有三點:

  1. 構造函數獲取C*指針並將其存儲在改進的類指針類中。
  2. p超出main函數的范圍時,析構函數刪除對象堆分配的C
  3. 重載->運算符使p->Do(); 將正確調用C::Do方法。

基本上,您要求實現的是標准auto_ptr類的部分功能。

考慮到在main()中使用Cpointer的方式,它必須像這樣實現:

class Cpointer
{
private:
    C* c:
public:
    Cpointer(C* _c) : c(_c) {}
    ~Cpointer() { delete c; }
    C* operator ->() { return c; }
};

問題是C的覆蓋'&'運算符也使用Cpointer,這種實現不適合這種用法。 內存損壞將發生,特別是如果在堆棧上聲明C實例(通常需要覆蓋'&'運算符)。 要真正使這項工作正常,必須修改C,要么停止使用Cpointer,要么包含Cpointer管理的引用計數。 無論哪種方式都違反了對C的“不要修改”限制。

這樣它編譯,不泄漏? 好。

class Cpointer
{
   public:
   Cpointer(C* c)
   {  delete c; }
  void Do()
  {  }
   Cpointer* operator ->()
   { return this; }
};
class C; //forward declaration
class Cpointer {
 public:
 C* mptr;

 Cpointer(C *cptr){
     mptr = cptr;
 }

 ~Cpointer(){
     delete mptr;
 }

 C* operator->() const {
     return mptr;
 }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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