是否可以分配两个不同类型的结构
Is it possible to assign two structures of different type?
我需要将一个结构分配给另一个类似的结构。只是名字不同。如果它是相同的名称,我们可以直接使用=
(赋值(运算符。
我不想使用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;
}
相关文章:
- 可以将两个相同类型的连续数组视为一个数组吗?
- [[no_unique_address]] 和两个相同类型的成员值
- C++将两个不同类型的向量的属性连接到新的向量中
- 如何在 c++ 中将两个不同类型的变量分配给一个变量
- 为什么我不能在同一行中定义两个相同类型的类的成员指针
- 我想添加两个字符串类型的矩阵.用户将不会输入行数或列的数量.用户将仅输入数组
- 是否可以分配两个不同类型的结构
- C++ 重载运算符 - 减去两个相同类型的对象
- C++:从模板中构造具有两个相同类型名称的海峡
- 比较C 中的两个数据类型
- 在C++中,当两个向量类型不同时,如何将值存储到向量内部的向量中
- 在整数数据类型和连续两个字符类型之后.第 2 个字符的数据类型跳过..为什么
- 确定两个矢量类型或一个矢量类型与标量类型之间的二进制运算结果的正确大小类型
- 在没有公共getter的情况下,比较两个相同类型的对象是否相等
- 在c++中编写两个基本类型之间的重载比较(==)
- 如何在yacc联合中保存出现在同一规则下的两个相同类型的对象
- Bison:$$和$1指向相同的内存位置(两个指针类型的联合YYSTYPE)
- c++中两个float类型变量的精确比较
- 比较两个不同类型的值
- 不能从两个相同类型的源之一创建std::string