C++ C++;使用';这';作为参数
我有一个大致如下的类:C++ C++;使用';这';作为参数,c++,C++,我有一个大致如下的类: class MeshClass { public: Anchor getAnchorPoint(x, y) { return Anchor( this, x, y ); } private: points[x*y]; } class Anchor { public: Anchor(&MeshClass, x, y) moveAnchor(x, y); } class Anchor; //forward
class MeshClass
{
public:
Anchor getAnchorPoint(x, y)
{
return Anchor( this, x, y );
}
private:
points[x*y];
}
class Anchor
{
public:
Anchor(&MeshClass, x, y)
moveAnchor(x, y);
}
class Anchor; //forward declaration
class MeshClass
{
public:
Anchor getAnchorPoint(int x, int y)
{
return Anchor(*this, x, y );
}
private:
int points[WIDTH*HEIGHT];
}
class Anchor
{
public:
Anchor(MeshClass &mc, int x, int y);
}
我想创建另一个类,它表示一个“锚”点,可以访问网格并修改该点,如下所示:
class MeshClass
{
public:
Anchor getAnchorPoint(x, y)
{
return Anchor( this, x, y );
}
private:
points[x*y];
}
class Anchor
{
public:
Anchor(&MeshClass, x, y)
moveAnchor(x, y);
}
class Anchor; //forward declaration
class MeshClass
{
public:
Anchor getAnchorPoint(int x, int y)
{
return Anchor(*this, x, y );
}
private:
int points[WIDTH*HEIGHT];
}
class Anchor
{
public:
Anchor(MeshClass &mc, int x, int y);
}
问题是,当我尝试在MeshClass::getAnchorPoint
方法中设置锚定时,类似于返回锚定(this,x,y)
,但因为this
是常量,所以我不能。作为一种解决方法,在我弄明白这一点之前,我让锚点接受对该点的引用,而moveAnchor直接移动该点
编辑:问题很可能是我试图使用引用时做的愚蠢的事情。我改为像往常一样使用指针,并且我可以传入这个
,而没有编译器的抱怨。我几乎可以肯定我得到了一个与常量相关的错误,但我无法重新创建它,所以我一定是疯了。为什么你认为这个
是常量<代码>此
是指针,不是引用。它不应该是返回锚点(*this,x,y)代码>?在创建锚时,是否可以将锚更改为接受一个常量MeshClass&
作为参数,或将其转换为(MeshClass)
?
我不确定是否可以使用<代码> COSTOSTCAST(这个)<代码>来删除<代码>的这个< <代码> > < /p> C++,这是一个指针,而不是引用。你可以这样做:
class MeshClass
{
public:
Anchor getAnchorPoint(x, y)
{
return Anchor( this, x, y );
}
private:
points[x*y];
}
class Anchor
{
public:
Anchor(&MeshClass, x, y)
moveAnchor(x, y);
}
class Anchor; //forward declaration
class MeshClass
{
public:
Anchor getAnchorPoint(int x, int y)
{
return Anchor(*this, x, y );
}
private:
int points[WIDTH*HEIGHT];
}
class Anchor
{
public:
Anchor(MeshClass &mc, int x, int y);
}
这不是一个问题。指针本身是常量,而不是它指向的值
你真正的问题在于:
class MeshClass
{
public:
Anchor getAnchorPoint(x, y)
{
return Anchor( *this, x, y );
}
private:
points[x*y];
}
嗨,对我来说,你不应该编译。。。是吗?它可能(还没有):)请记住(至少在普通的旧C中),如果没有指定类型,它默认为int,但会抛出一个警告。请发布您想要使用的实际代码及其生成的错误。(不是你如何试图解决这个错误。)现在有点难猜测你想做什么。是的,因为一开始,你应该有这样的东西:返回锚(*this,x,y);如果Anchor从技术上接收到一个ref.,这实际上是const,*这不是。从技术上来说,
这是不合格的。它不可修改,因为它是右值,而不是常量。这意味着此
具有类型Class*
,但不具有Class*const
。这可能是我的问题。我决定让Anchor接受一个指针而不是一个引用,在这种情况下,this
现在似乎可以作为一个参数正常工作。