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

C++ Pointer as a member of template class

本文关键字:成员 指针 C++      更新时间:2023-10-16

我对Template class和Template Function非常陌生。所以这一次我尝试创建自己的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类编写构造函数。是否建议将指针用作模板类的成员?提前谢谢。

问题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.

把它放在那里不是一个错误,但它是不需要的。