c++ - 是否可以在 C++ 中的静态成员方法中调用非静态成员方法?

标签 c++ static-methods

我怀疑这是可能的,但值得一问:我想从静态成员函数内部调用非静态成员函数。我想为该类的每个当前实例都这样做。可能吗?

当我在测试类中尝试此操作时,出现以下错误:

“不能在没有对象的情况下调用成员函数‘void TestClass::NonStaticMethod()’”

最佳答案

你可以用一些技巧来做到这一点。如果您想跟踪所有 实例,则必须在类构造时注册这些实例。当然,这很难做到正确,但这里有一个粗略的方法:

class Foo
{
    static std::unordered_set<Foo*> instances;

    void do_it();  // non-static member function

public:
    Foo()
    {
        instances.insert(this);
        // ...
    }

    // add copy constructor, move constructor, etc.

    ~Foo()
    {
        instances.erase(this);
        // ...
    }

    static void call_all()
    {
        for (Foo * p : instances) { p->do_it(); }
    }
};

您必须确保所有 构造函数执行注册。

关于c++ - 是否可以在 C++ 中的静态成员方法中调用非静态成员方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9346752/

相关文章:

java - 当尝试在静态方法调用中模拟静态方法调用时,Powermock 会调用初始方法

python - 如何将类中的staticmethod作为python中的装饰器?

c++ - 如何进行从 std::string_view 到 std::string 的转换

ios - 带有 xib 的 UIViewController 的单例

c++ - 如何在运行时摆脱 LD_LIBRARY_PATH?

c++ - sizeof(T) 可以产生的最大值是多少?

module - Crystal 有静态方法吗?

c++ boost::archives和mySql BLOB,反序列化错误

c++ - 阶乘用什么模板比较好