将一个结构的值复制到另一个结构
copying value of one struct to another
我想将一个结构的值复制到具有相同模板的另一个结构的值。以下是示例代码,其中struct list
是模板结构。调用func1()
必须将li
的内容复制到ref
。但是,当执行副本时会发生分割故障。我在哪里出错?
foo.cpp
#include<iostream>
#include <cstdlib>
class bar
{
public:
void func1(const list& li);
};
void bar::func1(const list& li)
{
listref ref = nullptr;
ref = (listref)malloc(sizeof(listref));
ref->a = li.a;//segfault occurs here
ref->b = li.b;
ref->c = li.c;
ref->d = li.d;
}
foo.h
#include<iostream>
struct list
{
std::string a;
int b;
int c;
const char* d;
};
typedef struct list* listref;
main.cpp
#include <iostream>
#include "foo.h"
#include "foo.cpp"
int main()
{
list l1;
std::string temp = "alpha";
l1.a = "alphabet";
l1.b = 60;
l1.c = 43;
l1.d = temp.c_str();
bar b;
b.func1(l1);
return 0;
}
您正在混合C和C 概念,这就是发生的!
您的类list
包含C 类型std::string
的成员,这是一个需要维护的语义的复杂类。
然后您对其进行malloc
!
即使您对 malloc
的尺寸论点是正确的(这不是;您只是给它的大小是指针的大小(,这也不能正确地构造任何东西。它应该是new
或std::make_unique
!
不要混合C和C 成语。
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何将数据从一个结构链接到另一个结构
- 是否可以使用智能指针成员设置具有另一个结构的结构?
- std::transform 将一个结构数组复制到另一个结构数组
- C++将结构复制到另一个程序的资源
- 结构新手,我对如何从 void 函数中返回值并将其放入另一个函数感到困惑
- 可以访问一个类中的播放器结构,但不能访问另一个类中的播放器结构
- 如何在另一个结构中初始化结构数组?
- 在另一个结构中声明内部结构会导致错误:结构使用无效
- 通过 C++ 中的另一个结构成员访问结构
- 难以从另一个结构中的函数返回结构
- 有没有办法将一个对象注入到另一个对象的结构中?
- 如何制作一个结构程序,在其中可以存储无限量的数据,以便每次您想要时都可以将另一个产品添加到列表中?
- 将一个结构的值复制到另一个结构
- 结构C++可以用 0 初始化,但不能用另一个 int 初始化
- 如何将矢量结构从一个标头文件传递到另一个标头文件中的类
- 是否可以定义一个在外部"C"块中继承另一个结构的结构?