创建自定义“字符串”(struct)副本

时间:2014-09-18 06:13:22

标签: c++

我试图创建一个复制我的卡片结构的函数。我只需要复制cvalue即可轻松启动。但是,我的cvalue不是复制,当读取1000时它仍然是5读。

#include <iostream>
#include <fstream>
#include <ctime>
#include <stdlib.h>
#include <string>

using namespace std;

//Structs
struct card 
{
    char suit[8];
    char rank[6];
    int cvalue;
    char location;
};

void copyCard(card destination, card source);

int main()
{
    card card1;
    card card2;
    card1.cvalue = 1000;

    card2.cvalue = 5;
    card *card1p = &card1;

    copyCard(card2, card1);
    cout << card2.cvalue << endl;

}

void copyCard(card destination, card source)
{
    card *myPointer;
    myPointer = &source;
    (*myPointer).cvalue = source.cvalue;
    myPointer = &destination;
    destination.cvalue = (*myPointer).cvalue;
}

1 个答案:

答案 0 :(得分:4)

如果您打算将source复制到目的地,那么您可以使source成为const &(修改它没有意义),并将目标作为引用或指针。

void copyCard(card& destination, const card& source)
{
  destination = source;
}

int main()
{
  card card1, card2;

  card1.cvalue = 1000;
  card2.cvalue = 5;

  copyCard(card2, card1);
  cout << card2.cvalue << endl;
}

但是,您的copyCard功能完全没有理由。您可以通过简单的分配将card1复制到card2

card2 = card1;