如何为= 0创建C 分配运算符
How to create c++ assignment operator for =0
在C 中,可以以0个不带施法的值的值来初始化指针类型(void*
/int*
/char*
(,但这对任何其他值都不起作用。是否可以将相同的行为灌输到定义的类中?=0
构造函数或==0
比较器?为了进行澄清,我正在尝试添加语法,以便可以将我的n维向量类分配给使用vec<n> dir = 0
编辑:使用void*作为构造函数参数的类型实际上是在起作用的,这是实现此目标的最佳方法吗?
从字面的 0
到 nullptr
有一个隐式转换, nullptr
的类型为 nullptr_t
。
因此,以下作品按照您想要的方式:
// Needed for nullptr_t
#include <cstddef>
struct A
{
A(std::nullptr_t) {}
};
int main()
{
A a = 0;
}
当然,这也意味着A a = nullptr
是有效的,但也许您可以使用它...
,您可能可以使用一些现代constexpr
和模板Shenanigans通过nullptr_t
进行间接完成此操作。
您无法制作一个接受的构造函数。
#include <cstddef>
class Foo
{
Foo(); // Construct from nothing at all
Foo(std::nullptr_t) // Construct from the null pointer value
};
分别使用
Foo foo_default;
Foo foo_null = nullptr;
因为0也是一个无效的指针值,因此您可以使用std::nullptr_t
过载。
Foo foo_zero = 0; // calls Foo(std::nullptr_t)
相关文章:
- 正在尝试重载二进制搜索树分配运算符
- 自定义先决条件对移动分配运算符有效吗
- C++ - 没有自定义交换功能的移动分配运算符?
- 强制复制分配超过移动分配运算符
- 在之后仍需要使用源对象时调用父移动分配运算符
- c++ 使用动态分配运算符反向数组元素
- 当存在用户定义的移动分配运算符时,已删除模板移动分配运算符
- C++ - 从移动分配运算符调用复制分配
- 不工作 复制分配运算符
- =删除用户定义的成员功能,除了构造函数,分配运算符C 11
- 返回对象如何与分配运算符一起工作
- 下标是否在分配运算符的右侧进行评估
- C++分配适用于已删除的分配运算符
- 用于删除复制/移动分配运算符的有效签名
- 使用新放置作为复制分配运算符不好吗?
- C++ - 父级中的 CRTP 分配运算符不起作用
- 复制派生类的分配运算符
- 未定义 Lambda 复制分配运算符
- 为什么标准在移动分配运算符中使用交换?
- 正确编写复制构造函数和分配运算符的方法