类定义错误:'SP'不是模板类型

时间:2016-08-24 23:28:56

标签: c++

我正在使用智能指针的自定义实现。代码如下。

#include <iostream>
class Person
{
    int age;
    std::string pName;

    public:
        Person(): pName(0),age(0)
        {
        }
        Person(std::string pName, int age): pName(pName), age(age)
        {
        }
        ~Person()
        {
        }

        void Display()
        {
            std::cout << "Name: " << pName << "Age: " << age << std::endl;
        }
        void Shout()
        {
            std::cout << "Ooooooooooooooooooo" << std::endl;

        }
};

/ *智能指针接口* /

class SP
{
private:
    Person* pData; // pointer to person class
public:
    SP(Person* pValue) : pData(pValue)
    {

    }
    ~SP()
    {
        /*pointer no longer requried*/
        delete pData;
    }

    Person& operator* ()
    {
        return *pData;
    }

    Person* operator-> ()
    {
        return pData;
    }
};

试图让它更通用。

template < typename T > class SP
{
    private:
       T* pData; // Generic pointer to be stored
    public:
       SP(T *pValue) : pData(pValue)
       {
       }
       ~SP()
       {
          delete pData;
       }

       T& operator*()
       {
          return *pData;
       }

       T * operator->()
       {
          return pData;
       }
};

int main()
{
    SP<PERSON> p(new Person("Scott", 25));
    p->Display();
    {
        SP<PERSON> q = p;
        q->Display();
        /*Destructor of q will be called here..*/
    }
    p->Display();
    /*Destructor of p will be called here.*/
    return 0;
}

当我尝试编译上面的代码时,我得到了错误。

smart_pointers.cpp:90:31: error: ‘SP’ is not a template type
 template < typename T > class SP
                               ^
smart_pointers.cpp: In function ‘int main()’:
smart_pointers.cpp:116:5: error: ‘SP’ is not a template
     SP<PERSON> p(new Person("Scott", 25));

这是什么原因?

1 个答案:

答案 0 :(得分:2)

您不能拥有同一类的两个定义。

struct S {};
template<typename T> struct S{};

重现您的编译器错误:http://ideone.com/7KpAPl

在这种情况下,您只需要模板定义。