为什么我不能用具有相同内容的两个结构交替分配? [英] Why can I not assign interchangeably with two structs that have identical contents?

查看:121
本文介绍了为什么我不能用具有相同内容的两个结构交替分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学习C和我遇到一些奇怪的:

I'm trying to learn C and I've come across something weird:

struct
{
  int i;
  double j;
} x, y;

struct
{
  int i;
  double j;
} z;

在这里,你可以看到我创建了两个结构 S中的是在他们的元素是相同的。

Here, you can see I created two structs that are identical in their elements.

为什么当我尝试分配 X = Z 它会产生一个编译错误,但 X = Y 不?他们有相同的内容,所以为什么我不能为它们分配来回相互搭配,不管?

Why is it that when I try to assign x = z it will generate a compile error but x = y does not? They have the same contents, so why can't I assign them back and forth with each other, regardless?

有没有什么办法可以让这个所以我的可以指定 X = Z ?或者,他们根本是相同的结构

Is there any way I can make this so I can assign x = z? Or do they simply have to be the same struct.

所有C大师可以点我在正确的方向?

Can any C gurus point me in the right direction?

推荐答案

它们具有相同的内容,但不是同一类型。如果它们旨在是同一类型的,只要的typedef X Z; 。如果它们不一样的东西,但只是碰巧包含相同的领域,最好是创建一个单独的功能,将正确地分配等领域。

They have the same content, but not the same type. If they are intended to be of the same type, simply typedef x z;. If they aren't the same thing, but just happen to contain the same fields, it's better to create a separate function that will assign the fields properly.


我一贯的风格在C声明结构包含了类型定义,所以我忘了提到它(对不起!)。下面是语法:

My usual style for declaring structs in C includes the typedef, so I forgot to mention it (sorry!). Here's the syntax:

typedef struct
{
  int foo;
  double bar;
} x;

/* Further down, if needed */
typedef x z;

这篇关于为什么我不能用具有相同内容的两个结构交替分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆