C++传递与另一种类型相同的类型

C++ passing a type that's identical to another type

本文关键字:类型 另一种 C++      更新时间:2023-10-16

谁能回答这个问题?

下面的代码将比我尴尬的问题更好地突出问题。

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
编译器通过

不随意转换类型来帮助您。假设您有一个宽度和高度floatRectangle类,以及一个高度和重量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){
}
相关文章: