在C++中,从同一类的另一个成员函数中调用成员函数,目标是C。

问题描述 投票:6回答:2

请考虑以下问题。

class A{

    //data members

    void foo()
    {
        bar();//is this possible? or should you say this->bar() note that bar is not static
    }
    void bar()
    {

    }
}//end of class A

如何从另一个对象中调用成员函数?而静态函数如何影响'this'的使用.是否应该在一个对象上调用函数?

c++ function static-methods member access-specifier
2个回答
7
投票

Nawaz是正确的:"this "是隐式的。 唯一的例外是如果foo是一个静态函数,因为在静态函数中没有'this'。 在这种情况下,你不能使用bar(),除非bar()也是一个静态函数,你根本不能使用this->bar()。


2
投票
bar();//is this possible? or should you say this->bar()

this 是隐式的。所以它们两个是等价的。你可以使用它们中的任何一个。但我又想,如果只是 bar() 够了,那为什么还要用 this->bar()?

使用 this 只有在有一些歧义的时候才用,否则就用简单一点的!

© www.soinside.com 2019 - 2024. All rights reserved.