C ++中内置类型的自定义构造函数
custom constructors for built-in types in c++
假设我定义了一个名为 Entity
的 class,它有一个数据成员,它是一个指向 int 的指针。例如
class Entity {
public:
int* ptr;
// other stuff
};
有没有办法为类型 int*
提供一个接受 Entity
对象的构造函数?如果我有一个名为 my_entity
的实体对象,我希望能够做这样的事情
int* p(my_entity);
或这个
int* p = my_entity;
这将要求编译器隐式调用带有 Entity
的 int*
的构造函数。
这可能吗? (我知道我可以在实体 class 中定义一个 public get_pointer()
方法并做类似 int* p = my_entity.get_pointer();
的事情,但这看起来很笨拙。)
您不能为基本类型创建构造函数。也没有必要使用构造函数来做到这一点,你可以像你已经提到的那样使用 getter ,或者你传递 Entity
和 int
并存储 int
到 Entity
。
您也可以像@Some programmer dude 所说的那样使用 user-defined conversion 并执行以下操作:
int *p = (int*)my_entity;
好吧,基本指针没有构造函数 - 从某种意义上说,没有隐式调用函数来初始化指针。
最接近的方法是使用用户定义的转换运算符函数
class Entity
{
public:
operator int *();
};
Entity::operator int *()
{
// return something appropriate that is of type int *
}
// sample usage in a function somewhere
int *p = some_entity; // implicitly conversion that calls the operator int *()
int *another_p = static_cast<int *>(some_entity); // explicit conversion
int *yet_another_p = some_entity.operator int *();
根据需要哪种形式的 const
限定,这有多种变体(例如,如果运算符函数不更改它作用于的对象,则它应该是 const
并且可能定义为 operator const int *()
).
必须确保正确处理由运算符函数编辑的指针 return。如果用户定义的运算符函数 return 是 some_entity
的成员,一旦 some_entity
不复存在,它就无法使用。同样,如果它使用动态内存分配(例如 return new
表达式的结果),调用者必须显式释放该内存以避免内存泄漏。
假设我定义了一个名为 Entity
的 class,它有一个数据成员,它是一个指向 int 的指针。例如
class Entity {
public:
int* ptr;
// other stuff
};
有没有办法为类型 int*
提供一个接受 Entity
对象的构造函数?如果我有一个名为 my_entity
的实体对象,我希望能够做这样的事情
int* p(my_entity);
或这个
int* p = my_entity;
这将要求编译器隐式调用带有 Entity
的 int*
的构造函数。
这可能吗? (我知道我可以在实体 class 中定义一个 public get_pointer()
方法并做类似 int* p = my_entity.get_pointer();
的事情,但这看起来很笨拙。)
您不能为基本类型创建构造函数。也没有必要使用构造函数来做到这一点,你可以像你已经提到的那样使用 getter ,或者你传递 Entity
和 int
并存储 int
到 Entity
。
您也可以像@Some programmer dude 所说的那样使用 user-defined conversion 并执行以下操作:
int *p = (int*)my_entity;
好吧,基本指针没有构造函数 - 从某种意义上说,没有隐式调用函数来初始化指针。
最接近的方法是使用用户定义的转换运算符函数
class Entity
{
public:
operator int *();
};
Entity::operator int *()
{
// return something appropriate that is of type int *
}
// sample usage in a function somewhere
int *p = some_entity; // implicitly conversion that calls the operator int *()
int *another_p = static_cast<int *>(some_entity); // explicit conversion
int *yet_another_p = some_entity.operator int *();
根据需要哪种形式的 const
限定,这有多种变体(例如,如果运算符函数不更改它作用于的对象,则它应该是 const
并且可能定义为 operator const int *()
).
必须确保正确处理由运算符函数编辑的指针 return。如果用户定义的运算符函数 return 是 some_entity
的成员,一旦 some_entity
不复存在,它就无法使用。同样,如果它使用动态内存分配(例如 return new
表达式的结果),调用者必须显式释放该内存以避免内存泄漏。