从类型*转换为类型,反之亦然

Casting from a Type* to Type and vice versa

本文关键字:类型 反之亦然 转换      更新时间:2023-10-16

是否可以从 c++ 中的预定义Type_pointer转换为其类型?

例如,我们定义了一个自定义 XType。我想做这样的事情,但出现错误:

XType* b;    
XType a = (XType) b; 

我想将指针本身传递给仅接受Type(而不是Type*)的函数

您应该使用 * 运算符取消引用指针:

struct Type {
  Type(Type*) {}
};
void f(Type t) {
}
int main () {
  Type a;
  Type* b = &a;
  // Q: how to invoke f() if I only have b?
  // A: With the dereference operator
  f(*b);
}

除了 @Rob φ 的提议之外,您还可以更改函数以接受指针。

实际上,如果您计划从给定函数中将指针传递给其他函数,则必须将指针(井或引用)作为参数获取,否则您将获得原始对象的副本作为参数,因此您将无法检索原始对象的地址(即指向)原始对象的地址。

如果你想省去重构,你可以做参考技巧:

void g(T* pt)
{
    // ...
}
void f(T& rt) // was: void f(T rt)
{
    cout << rt.x << endl; // no need to change, syntax of ref access
                          // is the same as value access
    g(&rt); // here you get the pointer to the original t
}
T* t = new T();
f(t);