我正在尝试在我的 C++ 类中访问带有指针的数组。
下面是我的课。
#include <iostream>
using namespace std;
class Poly
{
friend istream &operator>>(istream &, Poly &);
friend ostream &operator<<(ostream &, const Poly &);
public:
Poly();
Poly(int);
Poly(int, int);
Poly(const Poly &);
~Poly();
int getCoeff(int) const;
int getMaxPow() const;
void setCoeff(int, int);
void setMaxPow(int);
Poly operator+(const Poly &) const;
Poly operator+=(const Poly &);
Poly operator-(const Poly &) const;
Poly operator-=(const Poly &);
Poly operator*(const Poly &) const;
Poly operator*=(const Poly &);
Poly operator=(const Poly &);
bool operator==(const Poly &) const;
bool operator!=(const Poly &) const;
private:
int* coeffPtr;
int maxPow;
};
下面是我的构造函数
#include "poly.h"
#include <iostream>
using namespace std;
Poly::Poly() {
maxPow = 0;
int eq[1];
coeffPtr = &eq[0];
*coeffPtr = 0;
}
Poly::Poly(int coeff) {
maxPow = 0;
int eq[1];
coeffPtr = &eq[0];
*coeffPtr = coeff;
}
Poly::Poly(int coeff, int maxPower) {
maxPow = maxPower;
int eq[maxPower+1];
coeffPtr = &eq[0];
for(int i = 0; i < maxPower; i++)
{
*(coeffPtr+i) = 0;
}
*(coeffPtr+maxPower) = coeff;
}
Poly::Poly(const Poly &other) {
int eq[other.maxPow];
coeffPtr = &eq[0];
for(int i = 0; i < other.maxPow; i++)
{
*(coeffPtr+i) = other.getCoeff(i);
}
}
int Poly::getCoeff(int pow) const{
return *(coeffPtr+pow);
}
在我的 main 方法中,对 getCoeff(number) 的初始调用将返回数组中的正确元素,但似乎在初始访问后一切都发生了变化。
e.g.,
Poly A(5,7);
A.getCoeff(7); //returns 5
A.getCoeff(7); //returns random memory
我做错了什么?
谢谢!
最佳答案
您需要使用 coeffPtr = new int[...]
在堆上分配内存而不是制作coeffPtr
指向局部变量,例如局部变量int eq[...]
在你的构造函数中。
局部变量的内存分配在堆栈上,一旦局部变量超出范围,堆栈可能/将被覆盖。在你的情况下,一旦程序控制离开你的构造函数,coeffPtr
变成一个指向内存的悬空指针,内存的内容随时可能改变。写入此内存更糟糕,会导致代码其他位置的数据损坏或随机崩溃。
如果您在堆上分配内存,您还必须使用 delete[] coeffPtr
释放此内存在你的析构函数中,并在复制构造函数和复制赋值中处理内存......
(使用 std::vector<int>
而不是 int[]
可能是一个更好的主意,因为它使您从内存管理中解放出来。)
关于c++ - 在 C++ 中使用指针访问和操作数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33056604/