1

私は単一のエラーで立ち往生しています。これが私のコードです:

 template<class t>
 class smart_ptr{
    t *ptr;
 public: 
    smart_ptr(t *p):ptr(p){cout<<"smart pointer copy constructor is called"<<endl;} 

    ~smart_ptr(){cout<<"smart pointer destructor is called"<<endl;delete(ptr);}
    t& operator *(){cout<<"returning the * of pointer"<<endl;return(*ptr);}
    t* operator ->(){cout<<"returning the -> of pointer"<<endl;return(ptr);}
    t* operator=(const t &lhs){ptr=lhs;cout<<"assignement operator called"<<endl;}
   };
   class xxx{
            int x;
    public:
            xxx(int y=0):x(y){cout<<"xxx constructor called"<<endl;}
            ~xxx(){cout<<"xxx destructor is called"<<endl;}
            void show(){cout<<"the value of x="<<x<<endl;}
    };
 int main(int argc, char *argv[])
 {
    xxx *x1=new xxx(50);
    smart_ptr<xxx *> p1(x1);
    return 0;
 }

コンパイル中にエラーが発生します

smart_pointer_impl.cpp: 関数 'int main(int, char**)' 内:

smart_pointer_impl.cpp:27: エラー: 'smart_ptr::smart_ptr(xxx*&)' の呼び出しに一致する関数がありません</p>

smart_pointer_impl.cpp:7: 注: 候補は次のとおりです: smart_ptr::smart_ptr(t*) [with t = xxx*]

smart_pointer_impl.cpp:4: 注: smart_ptr::smart_ptr(const smart_ptr&)

解決策の助けは大歓迎です。

4

4 に答える 4

2

おそらくsmart_ptrであり、主に?の代わりにtemplate<class t>存在することを意図していました。smart_ptr<xxx>smart_ptr<xxx*>

于 2013-11-05T15:37:34.300 に答える
0

smart_ptrクラスをテンプレートとして宣言していません

template <TYPE>
class smart_ptr{
    TYPE *ptr;
public: 
    smart_ptr(TYPE *p):ptr(p){cout<<"smart pointer copy constructor is called"<<endl;} 

    ~smart_ptr(){cout<<"smart pointer destructor is called"<<endl;delete(ptr);}
    TYPE& operator *(){cout<<"returning the * of pointer"<<endl;return(*ptr);}
    TYPE* operator ->(){cout<<"returning the -> of pointer"<<endl;return(ptr);}
    TYPE* operator=(const TYPE &lhs){ptr=lhs;cout<<"assignement operator called"<<endl;}
};

また、ポインターを「xxx へのポインター」型として宣言していますが、テンプレート クラスはその型へのポインターです。試す:

smart_ptr<xxx> p1(x1);
于 2013-11-05T15:37:57.047 に答える
0

変更する必要があります::

smart_ptr<xxx *> p1(x1); to smart_ptr<xxx> p1(x1); 

それが動作します。

于 2013-11-05T15:54:43.873 に答える
0

コードの最初の行を忘れていることを願っています。

 template<class t>

そしてこの行:

smart_ptr<xxx *> p1(x1);

次のようにする必要があります。

smart_ptr<xxx> p1(x1);
于 2013-11-05T15:42:41.793 に答える