改变这是什么 [英] Changing what THIS is

查看:101
本文介绍了改变这是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以改变这一点吗?

  class foo {...} 

foo * fooinstance = new foo();
foo * otherfooinstance = new foo();

void
foo :: bar(){
this = otherfooinstance;
}

fooinstance-> bar();

对于那些想知道在什么情况下我会更改this指针的人是case。我不得不做一个树递归,我不得不删除中间节点..对于这个例子假设中间节点的删除有标题d。并且这些中间节点只有一个子节点。所以在lisp符号中,如果我们有一个树像



(g(d(i 4))(i 5))



函数removeIntermediates(tree)实际上会导致上述变成



(g(i 4)
$ b

,并且此IF指针可重新分配的伪代码将如下所示。

  DTREE :: removeIntermediates(){
this = child(0); removeIntermediates();
}

TREE :: removeIntermediates(){
for each child {child-> removeIntermediates();
}

我想这样做而不知道子节点是什么,转换为用于每个节点类型的不同函数,并具有用于其他类型的一般函数。可悲的是,我只是做了这样的事情。

  TREE :: removeIntermediates(){
为每个子{if(child-> name ==d){
setchild(child-> child(0));
child-> removeIntermediates();
}
else {child-> removeIntermediates();}
}


解决方案

C ++标准禁止在9.3.2 The this pointer中指定keyword this is a non-lvalue expression的分配。虽然,一些编译器仍然允许通过使用一个特定的编译时开关赋值,因为在早期草案的某个时候,C ++标准实际上允许赋值为this。



无论如何,很难想象一个情况下,你会真的想这样做,很可能有一个干净,美丽的方式来做。


Is there a way to change what THIS point to?

class foo{...}

foo* fooinstance = new foo();
foo* otherfooinstance = new foo();

void
foo::bar(){
    this = otherfooinstance;
}

fooinstance->bar();

for those of you who are wondering in what case I would change the this pointer here is case. I had to do a tree recursion where I had to remove intermediate nodes.. for this example lets assume the intermediate nodes of removal have the title d. and these intermediate nodes only have one child. So in lisp notation if we have a tree like

(g (d (i 4)) (i 5))

the function removeIntermediates(tree) would in effect cause the above to become

(g (i 4) (i 5))

and the pseudo code for this IF the this pointer was reassignable would look like the following..

DTREE::removeIntermediates(){
    this = child(0); removeIntermediates();
}

TREE::removeIntermediates(){
    for each child { child->removeIntermediates();
}

I wanted to do this without knowing what the child node was therefore making code factorable into different functions for each node type and having a general function for other types. Sadly, I just ended up doing something like this..

TREE::removeIntermediates(){
    for each child { if(child->name == "d") {
        setchild(child->child(0));
        child->removeIntermediates();
    }
    else { child->removeIntermediates();}
}

解决方案

C++ standard forbids assignment to this in "9.3.2 The this pointer" by stating that "keyword this is a non-lvalue expression". Although, some compilers still allow assignment to this by using a certain compile-time switch, because at some point in early drafts C++ standard actually allowed assignment to "this".

Anyway, it is quite hard to imagine a case where you would actually want to do that and it is very likely that there is a clean and beautiful way to do it.

这篇关于改变这是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆