繁体   English   中英

获取器和设置器的错误

[英]Error for getters and setters

我有一个顶点向量,我希望最初将vertice.setVisit设置为false或0。 我为此定义了一些getter和setter方法,但是却遇到了一些类型错误。 代码如下:

//Vector:
std::vector<project3::Vertex<VertexType, EdgeType>*> Vertice1;

//Class containing methods:
template <class VertexType, class EdgeType> class Vertex{
protected:
    //std::vector<std::pair<int, EdgeType>> VertexList;
    VertexType vertice;
    EdgeType edge;
    int num;
    int mark;
    //int status=0;

public:

    void setNum(int){ this.num = num; }
    int getNum() { return num; }
    int getMark(){ return mark; }
    void setVisit(int) { this.mark = mark; }
};

在某些函数中,我将值赋值为:

for(int i=0; i<g1.Vertice1.size(); i++)
{
    g1.Vertice1.at(i)->setNum(0);
    g1.Vertice1.at(i)->setVisit(0);
}

下面是在类的函数定义中为“ this.mark = mark”和“ this.num = num”的代码编译时遇到的错误。

Error: left of '.mark' must have class/struct/union
 Error: left of '.num' must have class/struct/union

这不是通过getter和setter分配值的正确方法吗?

在C ++中, this是一个指针类型。 尝试this->mark(*this).mark

编辑:正如理查德在下面指出的那样,还请确保命名您要分配的参数。 在上下文中, this->mark = markthis->mark = this->mark 除非mark是参数,否则在这种情况下, this实际上是不必要的。 所以实际上,你可以摆脱this在你的例子做这样的事情都在一起:

void setVisit(int newMark) { mark = newMark; }

问候,
丹尼斯·M。

将setNum和setVisit更改为以下内容

void setNum(int num) {this->num = num; }
void setVisit(int mark) {this->mark = mark; }

this是一个指针,因此您必须使用this->num

暂无
暂无

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

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