首页 文章

对象数组到另一个对象C中

提问于
浏览
0
#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

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

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

    What's the problem ?

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

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

    这是未定义的行为:您不能访问 clcList 数组的第6个元素,每个元素只有5个元素从0到4索引 . 根据您的编译器,这可能会导致程序崩溃,或者记忆腐败,或任何其他奇怪的事情 .

    How to solve it ?

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

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

相关问题