C++指针作为模板类的成员
C++ Pointer as a member of template class
我对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.
把它放在那里不是一个错误,但它是不需要的。
相关文章:
- 从成员指针到整个结构/类的强制转换
- OOP 中的单成员指针
- 使用结构成员指针在C++中填充结构
- 聚合初始化,将成员指针设置为同一结构成员
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 共享 C++ 的数据成员指针
- 如何声明指向成员内容的成员指针m_pmd/m_pmf并访问它们?
- 从类C++外部调用指向成员方法的成员指针
- 结构成员指针是否自动初始化为零?
- 如何删除类内类类型的类成员指针
- 是否打印指向已定义 int 的成员指针
- 指向常量的成员指针
- 通过此指针访问时的成员差异和自身的成员指针(简单的 QT 示例问题)
- 类数据成员指针的非类型模板参数包无法使用 gcc 编译
- 为什么我不能在同一行中定义两个相同类型的类的成员指针
- 将类成员指针传递给 Lambda 捕获列表 c++11
- 在单一实例类中将成员指针设置为 null 的正确方法是什么
- 无法删除在destructor中的成员指针的课程
- 删除对象而不调用成员指针的析构函数
- 当派生类的基类具有成员指针时,对其进行深层复制