小智 6
是的 - 你可以,而且这是怎么回事
class Foo
{
public:
static void staticFunc( const Foo & foo)
{
foo.memberFunc();
}
void memberFunc() const
{
staticFunc(*this);
}
};
Run Code Online (Sandbox Code Playgroud)
这是一种设计,除了递归之外,还演示了如何调用静态和非静态成员函数.
由于人们总是倾向于低调,这里是摘要:
您可以从静态成员函数中访问非静态成员,前提是您传入了类实例,或者是其指针或引用.对象的限定(换句话说,静态成员签名)将决定您是否可以从内部调用
const或同时调用两者const和non-const成员函数.
非静态成员数据/函数依赖于this指针 - 它基本上是指向访问/调用成员数据/函数的对象的指针.静态是类级别,不与单个对象关联.但是,如果将类实例/或实例本身的引用/指针传递给静态函数,则可以进行调用.
#include <iostream>
struct Eg {
Eg() : x(42), y(-42) {}
static void foo(Eg const&f) {
std::cout << "foo\n";
f.bar();
// we are good -- x is mutable
std::cout << f.x << std::endl;
f.x = 24;
std::cout << f.x << std::endl;
std::cout << f.y << std::endl;
// you need non-const access for the following
// so they don't work -- see foo signature
//f.y = -24; compile error -- const l-value
// f.barbar(); same as above
}
void bar() const { // const required since we have a const reference
std::cout << "bar\n";
}
void barbar() { // const required since we have a const reference
std::cout << "bar\n";
}
// note well the members
mutable int x;
int y;
};
int main() {
Eg ex;
Eg::foo(ex); // or ex.foo(ex);
}
Run Code Online (Sandbox Code Playgroud)
看看Singleton/factory方法模式 - 它们会引起您的兴趣.