getter 和 setter 的错误
我有一个顶点向量,我希望最初将 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 赋值的正确方法吗?
I have a vector of vertices and I wish to set vertice.setVisit as false or 0 initially. I defined some getters and setters for this, but getting some type error. Code is as per below:
//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; }
};
In some function I am assigning the values to it as :
for(int i=0; i<g1.Vertice1.size(); i++)
{
g1.Vertice1.at(i)->setNum(0);
g1.Vertice1.at(i)->setVisit(0);
}
Below is the error I am getting while compilation of the code for "this.mark=mark" and for "this.num=num" in the function definition in class.
Error: left of '.mark' must have class/struct/union
Error: left of '.num' must have class/struct/union
Isn't this the correct way to assign the values through getter and setters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C++ 中,
this
是指针类型。尝试this->mark
或(*this).mark
编辑: 正如理查德在下面指出的,也请确保将您的参数命名为你正在尝试分配。在上下文中,
this->mark = mark
与this->mark = this->mark
相同。除非mark
是一个参数,否则在这种情况下this
确实没有必要。所以实际上,您可以通过执行以下操作来在示例中一起摆脱this
:问候,
丹尼斯·M.
In C++,
this
is a pointer-type. Trythis->mark
or(*this).mark
EDIT: As Richard pointed out below, also be sure to name your parameters which you are trying to assign. In context,
this->mark = mark
is the same thing asthis->mark = this->mark
. Unlessmark
is a parameter,this
is really unnecessary in this case. So realistically, you can get rid ofthis
all together in your example by doing something like this:Regards,
Dennis M.
将 setNum 和 setVisit 更改为以下内容
Change setNum and setVisit to the following
this
是一个指针,因此必须使用this->num
。this
is a pointer, so you have to usethis->num
.