【发布时间】:2018-03-12 17:47:27
【问题描述】:
#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。
【问题讨论】:
-
小心,C 风格的数组与其他对象相比具有其他语义(在您的情况下,它们会衰减,并且可以照常分配这些指针)
-
cList[5] = cl[5];确实不复制/分配整个数组,只有一个元素(在这种情况下,它的大小也超过cl,调用 未定义的行为) -
不要使用 C 数组。使用 std::vector 或 std::array。
-
你把你的硬币放在一个数组里然后把那个数组放进你的钱包里吗?我将硬币直接放入钱包。
-
钱包 钱包 = Purse(coinsArray ,"John"); @manni66 这是老师教给我们的。