C++传递与另一种类型相同的类型
C++ passing a type that's identical to another type
谁能回答这个问题?
下面的代码将比我尴尬的问题更好地突出问题。
struct vector2d
{
float x,y;
};
struct point2d
{
float x, y;
}
void drawpoint(point2d point);
int main()
{
vector2d vec = {100, 100};
drawpoint(vec);
}
void drawpoint(point2d point)
{
...
}
我想知道为什么这不起作用。 另一种方法是通过中间堆 point2d 变量手动转换类型,但编译器会看到这一点并知道这不是必需的吗?
我在这里可能错过了一件非常简单的事情,提前感谢。
point2d pnt;
memcpy(&pnt, &vec, sizeof(pnt));
drawpoint(pnt);
或
point2d pnt = { vec.x, vec.y };
drawpoint(pnt);
或
drawpoint(point2d{vec.x, vec.y});
或
drawpoint(*(const point2d*)&vec); // UB, but will work on many implementations
编译器通过
不随意转换类型来帮助您。假设您有一个宽度和高度float
的Rectangle
类,以及一个高度和重量float
PatientInformation
类。如果您传递了错误的类型,您真的希望编译器无形地转换它吗?
请注意,以下代码将正常工作:
int main()
{
vector2d vec = {100, 100};
drawpoint(reinterpret_cast<point2d const&>(vec));
}
尽管如此,这里适当的解决方案是使用类型时更干净。向量传递给drawpoint
是没有意义的,就像将一个点传递给moveBy
是没有意义的一样。从类型的角度考虑,而不是从成员的角度考虑。
你不能
,你必须这样:
void main
{
vector2d vec = {100, 100};
point2d p;
p.x = vec.x;
p.y = vec.y;
Drawpoint(p);
}
你有一堆小的语法问题,你有没有尝试编译这个。
Struct, Void, and Float
不应大写
Void main
应该是 int main()
但最重要的是,您已经定义了 Drawpoint() 以将 Vector2D 作为参数,并且您正在尝试向它传递 point2d。C++类型安全,不会让您只用一种类型替换另一种类型。
您可以创建一个基类:
struct XY{
float x;
float y;
};
然后
struct vector2D: XY{
};
struct point2D: XY{
};
void drawPoint(XY& xy){
}
相关文章:
- 文本冒险游戏 - 如何区分一种项目类型与另一种项目类型以及如何构建项目类/子类
- 当 c++ 需要一种数据类型并获取另一种数据类型时会发生什么?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- void* 数组将元素转换为另一种类型
- 在 c++ 中将一种结构类型分配给另一种类型
- 将空基类优化对象强制转换为另一种类型是否会破坏严格的别名?
- 如何测试指针类型是否可以安全地转换为另一种指针类型?
- 将 32 位浮点数和不强制转换的 32 位整数与双精度进行比较,当其中一个值可能太大而无法完全适合另一种类型时
- 错误将结构复制到同一类型的另一种
- 何时与另一种类型兼容
- 将指向结构的指针转换为具有较少字段数的另一种结构类型
- 是否可以将一种函数类型转换为另一种采用相同参数但返回类型不同的函数类型
- 自动将一种 c++ 类型转换为另一种
- C 模板可以匹配(仅)一种类型的列表或另一种类型的列表
- 是否可以将一种类型的数组转换为大小不同的另一种类型的数组?
- 在比较中使用已强制转换为另一种类型的函数指针是否定义良好?
- 多态变体,并将一种类型的引用绑定到另一种类型的引用
- 如何使用模板元编程在 C++17 中将一种类型转换为另一种类型
- 将字符阵列施放到另一种类型中是否违反了严格的确定规则
- 创建一个从一种类型到另一种类型的别名