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

C++ 从一个结构复制到另一个不同类型的结构,c++,structure,C++,Structure,我正在VS2008中尝试这段代码 #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()

我正在VS2008中尝试这段代码

#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;
}
#包括
#包括
#包括
首先键入def结构
{
智力年龄;
std::字符串名;
}第一,;
类型定义结构(秒)
{
智力年龄;
字符名[20];
}第二;
无效复制_结构()
{
第一个s;
第二个f;
f、 年龄=15岁;

cout您应该使用基于成员复制的方法

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;
}
void copy_structure()
{
第一f;
^^
第二个s;
^^
s、 年龄=15岁;

CUT

这看起来像C但不象C++。你的当前代码也会把你的STD::string实例砖住。MycPy是危险的,不应该被使用,除非你有一个非常非常好的理由。到目前为止我还没有任何理由。 我的建议是:

#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;
}
#包括
#包括
使用名称空间std;
结构秒
{
智力年龄;
字符名[20];
};
结构优先
{
智力年龄;
字符串名;
第一个和运算符=(常数第二个和rhs);
};
//一些复制操作员
第一个和第一个::运算符=(常量第二个和rhs)
{
年龄=rhs.age;
name=rhs.name;
归还*这个;
}
int main()
{
第一个s;
第二个f;
f、 年龄=15岁;
姓名;
s=f;

为什么会有一个名字呢?到底是什么让你相信你可以简单地将
char
缓冲区按位复制到
std::string
对象中,然后得到一个有效的字符串?仅供参考:
struct\u second
大于20个字节。虽然这不是你最大的问题。为什么不指定你所负担的要求,并获得一个有效的字符串他们的解决方案是什么?@NIXIN您可能不会按照您将要做的那样做。:)要求是什么?
#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;
}