如何使用const和引用以及STL来解决这个恼人的错误?

时间:2015-07-26 21:44:50

标签: c++ constructor stl const

可以找到详细代码here in detail

Main.cpp的

#include "Point2d.h"
#include "Line2d.h"
#include "Rectangle2d.h"
#include "MatrixMemory.h"
#include "Matrix.h"
#include <iostream>
#include <vector>

int main()
{
    std::vector<Point2d> points;
    std::vector<Line2d> lines;
    std::vector<Rectangle2d> rectangles;
    //std::vector<MatrixMemory> matMem;
    //std::vector<Matrix> mat;

    return 0;
}

我收到此错误消息:

1>------ Rebuild All started: Project: Matrix, Configuration: Debug Win32 ------
1>Deleting intermediate and output files for project 'Matrix', configuration 'Debug|Win32'
1>Compiling...
1>reference.fixer.cpp
1>2d.tran.cpp
1>Rectangle2d.cpp
1>Polygon2d.cpp
1>Line2d.cpp
1>Bits.cpp
1>Vector2d.cpp
1>MatrixMemory.cpp
1>.\MatrixMemory.cpp(32) : error C2662: 'MatrixMemory::GetItem' : cannot convert 'this' pointer from 'const MatrixMemory' to 'MatrixMemory &'
1>        Conversion loses qualifiers
1>Matrix.cpp
1>main.cpp
1>translation.3d.cpp
1>translation.2d.cpp
1>scaling.2d.cpp
1>rotation.2d.cpp
1>clipping.2d.weiler.atherton.cpp
1>clipping.2d.sutherland.hodgman.cpp
1>clipping.2d.midpoint.subdiv.cpp
1>clipping.2d.liang.barsky.cpp
1>clipping.2d.cohen.sutherland.cpp
1>Generating Code...
1>Build log was saved at "file://e:\Developer-Workspace\MyGraphicsLibraryImplementation\Debug\BuildLog.htm"
1>Matrix - 1 error(s), 0 warning(s)
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

错误消息来自以下代码段:

MatrixMemory.cpp
...................................

MatrixMemory & MatrixMemory :: operator=(const MatrixMemory  & rhs)
{
    if(rowSize!=rhs.rowSize || colSize!=rhs.colSize)
    {
        DeallocateMemory();
        AllocateMemory(rhs.rowSize, rhs.rowSize);
    }

    for(int i=0 ; i<rowSize ; i++)
    {
        for(int j=0 ; j<colSize ; j++)
        {
            this->SetItem(i, j, rhs.GetItem(i, j));
        }
    }

    return *this;
}

void MatrixMemory :: SetItem(int r, int c, double value)
{   
    if((r>=0 && r<rowSize) && rowSize>0)
    {
        if((c>=0 && c<colSize) && colSize>0)
        {
            data[r][c] = value;
        }
    }   
}

double MatrixMemory :: GetItem(int r, int c)
{
    double ret = INVALID;

    if((r>=0 && r<rowSize) && rowSize>0)
    {
        if((c>=0 && c<colSize) && colSize>0)
        {
            ret = data[r][c];
        }
    }
    return ret;
}

如您所见,无法将MatrixMemory::GetItem声明为const。 Coz,它包含一些逻辑。

如何解决问题?

沮丧的选民和亲密的选民,你能澄清一下原因吗?

1 个答案:

答案 0 :(得分:4)

在赋值运算符中调用rhs.GetItem(i, j)时,编译器要求rsh为非常量。这是因为GetItem未被声明为常量成员函数。但是,rhs被声明为常量引用,因此是错误。

声明const来解决问题:

double GetItem(int r, int c) const; // line 383; also on line 466
//                           ^^^^^

这允许您在常量对象上或通过GetItem指针和引用调用const成员函数。