C ++指针作为模板类的成员

时间:2016-07-29 05:30:41

标签: c++ templates

我是模板类和模板功能的新手。所以这一次我尝试创建自己的Nullable类,它允许任何对象具有值或null值。

template<typename _Type>
class Nullable
{
private: 
    _Type *_Pointer
public:
    Nullable::Nullable(const _Type &x)
    {
        this->_Pointer = new _Type(x);
    };

但是,当我编译它时,它会返回2个错误:

  • C2059:语法错误:'this'
  • C2238:';'
  • 之前的意外令牌

在上面的构造函数的行上。

所以请向我解释如何为Template类正确编写构造函数。是否建议使用Pointer作为Template Class的成员? 提前谢谢。

1 个答案:

答案 0 :(得分:3)

问题1

您在行中缺少;

_Type *_Pointer;
              ^^ missing

问题2

如果构造函数是内联定义的,则不能使用范围运算符。

更改

Nullable::Nullable(const _Type &x) { ... }

Nullable(const _Type &x) { ... }

挑剔

在构造函数定义的末尾不需要;

Nullable(const _Type &x)
{
    this->_Pointer = new _Type(x);
};
 ^^ Remove it.

将它放在那里并不是错误,但不需要它。