从一个结构复制到另一个不同类型的结构

Copy from one structure to another structure of different type

本文关键字:结构 另一个 同类型 复制 一个      更新时间:2023-10-16

我正在与 vs 2008 中尝试这段代码

#include <stdio.h>
#include <iostream>
#include <string>
typedef struct _first
{
    int age;
    std::string name;
}first;
typedef struct _second
{
    int age;
    char name[20];
}second;
void copy_structure()
{
    first s;
    second f;
    f.age = 15;
    cout<<"Enter the name"<<endl;
    fgets(f.name, 20, stdin);
    memcpy(&s,&f,20);
    cout << "Name: " << s.name << endl;
    cout << "Age: "<< s.age << endl;
}
int main()
{
    copy_structure();
    return 0;
}

在构建时我没有收到任何错误,但是当我运行时,这里的名称字段为空

cout << "Name: " << s.name << endl; 

在这里没有得到任何输出,有人可以帮助我解决这个问题吗?

应使用基于成员复制的方法。例如

void copy_structure()
{
    first f;
          ^^
    second s;
           ^^
    s.age = 15;
    cout<<"Enter the name"<<endl;
    fgets(s.name, 20, stdin);
    f.age = s.age;
    f.name = s.name;
    cout << "Name: " << f.name << endl;
    cout << "Age: "<< f.age << endl;
}

否则,类型std::string的对象名称的内部将被覆盖,程序将具有未定义的行为。

这看起来像C,但不像C++...您当前的代码也会使您的 std::string 实例变砖。Memcpy是危险的,不应该使用,除非你有非常非常充分的理由。到目前为止,我从来没有理由这样做。

我的建议:

#include <iostream>
#include <string>
using namespace std;
struct second
{
    int age;
    char name[20];
};
struct first
{
    int age;
    string name;
    first& operator=(const second& rhs);
};
// some operator for copying
first& first::operator=(const second& rhs)
{
    age = rhs.age;
    name = rhs.name;
    return *this;
}

int main()
{
    first s;
    second f;
    f.age = 15;
    cout << "Enter your name" << endl;
    cin >> f.name;
    s = f;
    cout << "Name: " << s.name << endl;
    cout << "Age: " << s.age << endl;
    return 0;
}

当然,这是可以改进的。您通常宁愿使用类而不是结构。而且您可能还会有一个运算符>>其次。

相关文章: