//Where is my problem?
#include<iostream>
#include<string>
#include<cassert>
using namespace std;
enum cls{ bb, bc };
const int max = 10;
class Ship
{
private:
char*name;
cls clas;
int numGuns;
public:
Ship(char* =" ", cls=bb, int=0);
Ship(const Ship &);
~Ship();
Ship& operator=(Ship &);
char*getName()const;
cls getClas()const;
int getNumGuns()const;
void print()const;
};
Ship::Ship(char*n, cls c, int num)
{
name = new char[strlen(n) + 1];
assert(name != NULL);
strcpy(name, n);
clas = c;
numGuns = num;
}
Ship::Ship(const Ship & s)
{
name = new char[strlen(s.name) + 1];
assert(name != NULL);
strcpy(name, s.name);
clas = s.clas;
numGuns = s.numGuns;
}
Ship::~Ship()
{
delete[]name;
}
Ship& Ship::operator=(Ship & sh)
{
if (this != & sh)
{
delete[]name;
name = new char[strlen(sh.name) + 1];
assert(name != NULL);
strcpy(name, sh.name);
clas = sh.clas;
numGuns = sh.numGuns;
}
return*this;
}
char* Ship::getName()const
{
return name;
}
cls Ship::getClas()const
{
return clas;
}
int Ship::getNumGuns()const
{
return numGuns;
}
void Ship::print()const
{
cout << "Name: " << name << endl << "Clas: " << clas << endl << "numGuns:" << numGuns << endl;
}
class Navy
{
private:
char* country;
int size;
Ship*arr;
public:
Navy(char* =" ", int=0);
Navy(const Navy&);
~Navy();
Navy& operator=(const Navy&);
void addShip(Ship);
void printNavy()const;
};
Navy::Navy(char* c, int s)
{
country = new char[strlen(c) + 1];
assert(country != NULL);
strcpy(country, c);
size = s;
arr = new Ship[s];
assert(arr != NULL);
}
Navy::Navy(const Navy& n)
{
country = new char[strlen(n.country) + 1];
assert(country != NULL);
strcpy(country, n.country);
size = n.size;
arr = new Ship[n.size];
assert(arr != NULL);
for (int i = 0; i < n.size; i++)
arr[i] = n.arr[i];
}
Navy::~Navy()
{
delete[]country;
for(int i=0;i<size;i++)
{
delete[]arr;
}
}
Navy& Navy::operator=(const Navy& n)
{
if (this != &n)
{
delete[]country;
for(int i=0;i<size;i++)
{
delete[]arr;
}
country = new char[strlen(n.country) + 1];
assert(country != NULL);
strcpy(country, n.country);
size = n.size;
arr = new Ship[n.size];
assert(arr != NULL);
for (int i = 0; i < n.size; i++)
arr[i] = n.arr[i];
}
return *this;
}
void Navy::addShip(Ship s)
{
arr[size] = s;//??
size++;
}
void Navy::printNavy()const
{
cout << "Country of Navy: " << country << endl;
for (int i = 0; i < size; i++)
{
arr[i].print();
}
}
int main()
{
Ship s1("A", bb, 10);
s1.print();
Ship s2("A1", bb, 11);
Navy n("GR", 3);
n.addShip(s1);
n.addShip(s2);
n.printNavy();
system("pause");
return 0;
}
这是一个创建海军的程序,它有一系列的船只和国家作为私人组件。我认为这是一个非常简单的程序,但我不能强调它为什么会抛出异常。我是c ++的新手,所以如果有人告诉我问题出在哪里,我会很高兴。
答案 0 :(得分:0)
void Navy::addShip(Ship s)
{
arr[size] = s;//??
size++;
}
这里你运行数组的边界(因为size成员最初等于数组中元素的数量)!您应该记录您的船只并动态重新分配阵列!
我建议摆脱动态内存分配(new
)并使用std::vector
来存储你的对象。