【发布时间】:2016-10-21 03:56:22
【问题描述】:
我有一个关于 c++ 的小项目。 项目需要我写一个模板类,比如说A类。 我对A的要求很少,其中:
- A 实现中不允许动态分配。
- A 包含 T 类型的参数(不是指针,因此没有“新”)。
- A 可以为空(即未初始化)。
-
可以通过以下方式初始化 A:
A<int> a; A<int> a(5); A<int> a = 5; A<int> a = Empty;
我对前 3 种初始化类型没有任何问题,但是对于最后一个选项我有点无能为力。
Empty 是我应该根据需要定义的一些类。我最初的方向是创建一个(空)类 EmptyClass:
class EmptyClass {};
静态实例化一个名为 Empty 的对象(因此任何使用 A 类的对象也都知道 Empty):
static EmptyClass Empty;
就是这样。显然,它不起作用。
整个(相关的)模板声明:
class A{
private:
T _Value;
bool _empty;
public:
A();
A(const T value);
A(const EmptyClass none);
A(const A& opt);
A(const EmptyClass & none);
//Checks if the object is empty
const bool isEmpty() const;
//Destructor
~Optional();
A<T>& operator=(const EmptyClass& rhs);
A<T>& operator=(const A<T>& rhs);
};
目前我在这一行遇到错误:
A<int> optionalInt = Empty
错误是:
错误:从 'EmptyClass (*)()' 到 'int' 的无效转换 [-fpermissive]
我只能使用 c++98 标准。 希望得到解决这个问题的任何方向。
谢谢!
【问题讨论】:
-
你需要展示整个模板类声明。
-
您可能想了解Boost optional(将在C++17 标准中作为
std::optional引入)。如果您不想使用它,那么至少您可以将其用作创建自己的可选类的参考。 -
至于您要问的问题,请编辑问题以包含Minimal, Complete, and Verifiable Example,或者至少向我们展示
Empty的声明。 -
嗨,谢谢。编辑了我原来的帖子,我希望现在已经足够好了。
标签: c++ templates casting operators