4

当我通过同事编写的代码时,在某个地方,他们使用:

this->doSomething(); //-->case A
doSomething(); //-->case B

事实上,我不确定 *this 指针的用途... :(

另一个与参数匹配的问题:

obj.doOperation();  //-->case C
(&obj)->doOperation(); //-->case D

事实上,这两种情况都在执行所需的操作,这仅仅是让代码看起来更复杂的一种方法吗?

您对以上两个问题有何建议?什么时候使用它们合适,为什么?

4

3 回答 3

5

这不是您问题的答案,但请注意两个片段可能会做不同的事情:

namespace B { void doSomething() {} }

struct A {    
    void f()
    {
        using B::doSomething;
        this->doSomething(); // call A::doSomething
        doSomething(); // calls B::doSomething
    }

    int a;
    void g(int a)
    {
        this->a = a; // assigns argument to member
    }

    A* operator & () { return this; }
    void doOperation() {}
    void doSomething() {}
};

void g(A &obj)
{
    obj.doOperation();  // calls A::doOperation directly
    (&obj)->doOperation(); // calls A::operator & first
}
于 2010-09-29T15:41:35.477 回答
3

Cases B and C are always the appropriate way. Cases A and D are equivalent and do nothing different.

A few exceptions to that:

  • If the class has an overloaded operator& that does surprising things, then case D could do something different that C. Actually having classes which do this is not recommended, since it would be confusing.
  • If there is a local variable doSomething (or something else of that name in the local scope), then A would refer to a different doSomething than B. Again it isn't recommended to get yourself into such a situation, better give different names to different things.
于 2010-09-29T15:47:34.557 回答
1

C 和 D 不同。如果是虚拟的,case D 将执行虚拟调用,如果不是引用doOperation,case C 将执行非虚拟调用。obj然而,这假设operator&并且operator->没有被重载。

我倾向于使用 A 而不是 B,因为可能有一个本地doSomething标识符。在模板代码内部,情况可能会变得更糟(尽管我现在无法提供精确的示例)。这是一个好习惯。

于 2010-09-29T15:59:20.673 回答