【发布时间】:2020-07-03 11:08:54
【问题描述】:
我创建了一个头文件 polygon.h 和一个 polygon.cpp
多边形.h:
#pragma once
#include <iostream>
using namespace std;
class Polygon {
protected:
int numSides;
int* sides;
public:
Polygon(int nSides);
Polygon(const Polygon&);
~Polygon();
int getNumOfSides();
int perimeter(); // perimeter = hekef
bool operator==(Polygon);
};
多边形.cpp:
#include <iostream>
#include "Polygon.h"
using namespace std;
Polygon::Polygon(int nSides) {
this->numSides = nSides;
this->sides = new int[nSides];
if (nSides != 3 && nSides != 4)
{
cout << "Enter sides for polygon: " << endl;
for (int i = 0; i < nSides; i++)
cin >> this->sides[i];
}
};
Polygon::Polygon(const Polygon& other) {
this->numSides = other.numSides;
this->sides = new int[other.numSides];
for (int i = 0; i < this->numSides; i++)
this->sides[i] = other.sides[i];
};
Polygon::~Polygon() {
delete [] this->sides;
};
int Polygon::getNumOfSides() {
return this->numSides;
};
int Polygon::perimeter() {
int sum = 0;
for (int i = 0; i < this->numSides; i++)
sum += this->sides[i];
return sum;
};
bool Polygon::operator==(Polygon other) {
return (this->getNumOfSides() == other.getNumOfSides() && this->perimeter() == other.perimeter());
};
我也创建了一个主文件,但没关系。
问题是,例如当我将值 5 传递到 numSides 时,程序应该从 sides 创建一个具有 5 个插槽的新动态 int 数组这个例子,但相反,在调试它时,我发现它只创建了 1 个插槽,就好像它只是一个常规整数一样,当我将 5 个值设置为 sides 时(对于这个例子来说,5 ),sides 最终只包含我输入的第一个值。
如果有人能帮助甚至解决这个问题,我会很高兴:)
【问题讨论】:
-
调试器只知道
sides是一个指针,不知道它指向了多少个元素。如果您使用std::vector,您将能够看到所有点。 -
显而易见,
std::vector<int> sides;而不是手动内存管理将使这变得微不足道,并且作为奖励,还消除了对numSides成员的需要。也就是说,您对“调用”代码的使用是相关的。它应该包含在您的问题中。您还缺少一个复制赋值运算符,因此引入了 rule of three 违规的配方。要做的事情。