1

I'm trying to implement a container that allocated memory to the heap, but it seems as though my base constructor and my argument constructor don't like each other. Below, I've posted the code without anything commented out. As it stands, it crashes.

#include <iostream>
using namespace std;

class foo
{
public:
    foo() {size=1; vals = new double[1]; vals[0]=0;}
    ~foo() {delete[] vals;}

    foo(const foo& other)
    {
        size=other.getsize();
        delete[] vals;
        vals = new double[size];
        for(long unsigned i=0; i<size; i++)
            vals[i]=other[i];
    }

    foo& operator=(const foo& other)
    {
        size=other.getsize();
        delete[] vals;
        vals = new double[size];
        for(long unsigned i=0; i<size; i++)
            vals[i]=other[i];
        return *this;
    }

    foo(double* invals, long unsigned insize)
    {
        size=insize;
        delete[] vals;
        vals = new double[size];
        for(long unsigned i=0; i<size; i++)
            vals[i]=invals[i];
    }

    double operator[](long unsigned i) const {return vals[i];}

    long unsigned getsize() const {return size;}
private:
    double* vals;
    long unsigned size;
};


int main()
{
    double bar[3] = {5,2,8};
    foo B(bar, 3);

    cout<< B[0]<< " "<< B[1]<< " "<< B[2]<<endl;    //couts fine

    foo A;    //crashes here

    return 0;
}

However, when I change main to be:

int main()
{
    double bar[3] = {5,2,8};
    foo B(bar, 3);

    cout<< B[0]<< " "<< B[1]<< " "<< B[2]<<endl;    //couts fine

    foo A();    //works now

    return 0;
}

It runs fine. But then I can't assign A = B because it thinks foo is a function or something.

4

1 回答 1

3

我假设你有一些非常令人信服的理由不在std::vector<double>这里使用......

但无论如何......在你的复制构造函数中,你不想delete[] vals.

foo(const foo& other)
{
    size=other.getsize();
    vals = new double[size];
    for(long unsigned i=0; i<size; i++)
        vals[i]=other[i];
}

当复制构造函数被调用时,你的对象还没有被初始化,所以vals*甚至没有指向任何有效的东西。因此,删除它会调用未定义的行为(并且您的程序崩溃。)您只需要delete[] vals在您的赋值运算符中。

此外,当您声明Foo变量时A,您不希望变量名后面有这些括号。说啊:

foo A;

当您将这些括号放在变量名之后时,您实际上是在使用从 C 继承的语法编写函数声明,并A成为函数指针类型。

于 2013-05-18T03:18:29.747 回答