从类型*转换为类型,反之亦然
Casting from a Type* to Type and vice versa
是否可以从 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);
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- C++ - 使用结构数据类型将单词中的单个小写字符更改为大写,反之亦然
- std::memcpy结构,具有TriviallyCopyable类型T的紧密封装成员到T的数组,反之亦然
- 从类型*转换为类型,反之亦然
- 将枚举类型转换为整数,反之亦然
- 视觉C++:如何将'PCZZWSTR'类型更改为'char',反之亦然?
- 通过套接字将对象(XML输出或任何c++对象类型)从服务器传递到客户机,反之亦然
- 如果允许将int赋值给float(反之亦然),是否不类型安全?