将Object Array转换为另一个Object C ++

时间:2017-10-01 12:08:07

标签: c++ arrays object

#include <iostream>
#include <string>
#include "coin.h"
#include "purse.h"
//include necessary files

using namespace std;
/*
 Object Composition:  An object can comprise of many other objects; eg handphone has battery, sim card, sd card, etc
  To program object composition; we declare a data member (variable) that is of other Class type;
 */

int main(){
    //   i.Create an array of Coin 5 objects
        Coin a(5),b(10),c(20),d(50),e(100);
        Coin coinsArray[5]; 
        coinsArray[0] =a;
        coinsArray[1] =b;
        coinsArray[2] =c; 
        coinsArray[3] =d; 
        coinsArray[4] =e; 



    //ii.Create an instance of Purse object with the array in i)
        Purse purse = Purse(coinsArray ,"John");

    //iii.Compute and display the total value stored in the Purse object in ii).
    cin.ignore();
}


#include <iostream>
#include <string>
#include "coin.h"
#include "purse.h"
using namespace std;

//write the definition for the Purse class

Purse::Purse(Coin cl[5], string o)
{
    cList[5] = cl[5];
    owner = o;
}

    string Purse::getOwner()
    {
    return owner;
    }

    void Purse::setOwner(string o)
    {
      owner =o;
    }

    void Purse::displayCoins()
    {
       cout<< "Display";
    }


    int Purse::computeTotal()
    {
     int total = 6;

         return total;
        }


#pragma once
#include <iostream>
#include <string>
#include "coin.h"
using namespace std;
/* Object Composition:  An object can comprise of many other objects; eg handphone has battery, sim card, sd card, etc
  To program object composition; we declare a data member (variable) that is of other Class type;
  Purse contains Coin objects - this is object composition
 */
class Purse
{
  private:
    Coin cList[5];
    string owner;
  public:
    Purse(Coin [] ,string="");
    string getOwner();
    void setOwner(string o);
    void displayCoins();
    int computeTotal();



};

嗨,我创建了5个Coin数组对象放入Purse对象,但是我一直得到未处理的异常。有没有人遇到过这个错误?错误是当我实例化钱包时。

CoinProject.exe中0x5240ad7a(msvcp100d.dll)的第一次机会异常:0xC0000005:访问冲突读取位置0xccccccd0。 CoinProject.exe中0x5240ad7a(msvcp100d.dll)的未处理异常:0xC0000005:访问冲突读取位置0xccccccd0。

1 个答案:

答案 0 :(得分:0)

Purse的构造函数不能执行您想要执行的操作:

Purse::Purse(Coin cl[5], string o)
{
    cList[5] = cl[5];
    owner = o;
}

有什么问题?

数组cl不是按值传递,而是通过引用传递。您在此定义该数组的大小为5个元素。

表达式cList[5] = cl[5]表示数组cl的项目编号5(因此这个5个元素的数组的第6个元素)将被复制到数组{{的项目编号5中1}}(所以也是5个元素数组的第6个元素)。

这是未定义的行为:您不能访问cListcl数组的第6个元素,每个元素只有5个元素从0到4索引。根据您的编译器,这可以用于例如导致程序崩溃,或内存损坏,或任何其他奇怪的事情。

如何解决?

如果您已经了解了循环,请使用循环来复制数组的每个元素。如果没有,请逐个复制元素(从0开始)。

P.S。:并告诉你的老师你听说过矢量比数组要好得多(即可以在一条指令中复制它们)。