简体   繁体   English

C++:编译向量模板 class 时出现段错误

[英]C++: Segfault when compiling vector template class

I'm learning C++ and going through and exercise of creating a custom vector template class, which looks like我正在学习 C++ 并练习创建自定义矢量模板 class,它看起来像

template<class T> class Vector
{
private:
    std::vector<T> mData; // data stored in vector
    int mSize; // size of vector
public:
// Constructor
    Vector(int size)
    {
        assert(size > 0);

        mSize = size;
        //std::vector<T> mData;
        mData.resize(mSize);
        for (int i = 0; i < mSize; i++)
        {
            //mData.push_back(0);
            mData[i] = 0;
        }
    }
// Get/set values
    T& operator[](int i)
    {
        assert(i >= 0 && i < mSize);
        return mData[i];
    }

    T const& operator[] (int i)const
    {
        assert(i >= 0 && i < mSize);
        return mData[i];
    }
...
}

I'm trying to overload the unary - operator by doing:我正在尝试通过执行以下操作来重载一元 - 运算符:

public:
    Vector operator-() const
    {
        Vector v(mSize);
        for (int i = 0; i < mSize; i++)
        {
            v[i] = 0 - mData[i];
        }
        return v;
    }

but this produces a segfault when compiling (with no futher explanation).但这会在编译时产生段错误(没有进一步的解释)。 I have multiple other similiar functions in the template which seem to work.我在模板中有多个其他类似的功能似乎可以工作。 In another template for a matrix class, I also have:在矩阵 class 的另一个模板中,我还有:

public:
    Matrix operator-() const // unary -
    {
        Matrix mat(mNumRows, mNumCols);
        for (int i = 0; i < mNumRows; i++)
        {
            for (int j = 0; j < mNumCols; j++)
            {
                mat(i,j) = -mData[i*mNumCols + j];
            }
        }
        return mat;
    }

which produces no errors.这不会产生错误。 I am not very familiar with memory issues yet.我对 memory 问题还不是很熟悉。 Is the whole syntax wrong and am I just lucky that the matrix function produces no errors?整个语法是否错误,我是否幸运矩阵 function 没有产生错误?

Error was not during compiling but running错误不是在编译期间而是在运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM