是否可以分配两个不同类型的结构

Is it possible to assign two structures of different type?

本文关键字:两个 同类型 结构 分配 是否      更新时间:2023-10-16

我需要将一个结构分配给另一个类似的结构。只是名字不同。如果它是相同的名称,我们可以直接使用=(赋值(运算符。

我不想使用memcpy()因为它会复制位。

struct first {
  int i;
  char c;
};
struct second {
  int i;
  char c;
  //we can overload assignment operator to copy field.
  void operator = ( struct first& f) {
      i=f.i;
      c=f.c;
  }
};
int main()
{
  struct first f;
  f.i=100;
  f.c='a';
  struct second s=f; 
}

但是我遇到编译错误。

错误:请求从"第一"转换为非标量类型"第二"。

不确定是否可能?

你需要

一个构造函数才能使用

struct second s=f;

如:

struct second{
  int i;
  char c;
  second(first const& f) : i(f.i), c(f.c) {}
  ...
};

要使用赋值运算符,请使用:

second s;  // No need to use struct in C++
s = f;

顺便说一句,operator=函数的正确接口和实现应该是:

second& operator=(first const& f)
{
   i=f.i;
   c=f.c;
   return *this;
}

按如下方式使用。然后它就会起作用。或者创建复制构造函数。

#include <iostream>
using namespace std;
struct first{
int i;
char c;
};
struct second{
int i;
char c;
//we can overload assignment operator to copy field.
void operator = ( struct first& f)
{
    i=f.i;
    c=f.c;
}
};
int main()
{
  struct first f;
  f.i=100;
  f.c='a';
  struct second s;
  s=f; 
}