Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我试图找到如何从静态函数中获取非静态变量的方法?
在静态函数中,我想从非静态变量中获取值。
有可能的?
class test { private: static void test(); string test; }
这是不可能的。静态成员函数只能访问静态类成员。这也是有道理的,如果你认为你可以调用
test::test();
无需实例化对象。事实上,在执行上面的代码时,甚至可能没有一个类实例。
如果您需要从静态成员函数访问非静态类成员,则需要将类实例传递给它,无论是指针还是引用。但是,当您这样做时,您不妨将静态成员函数设为非静态。
你不能那样做。当您使用静态函数时,您处于静态上下文中。只能访问静态成员,其他成员不存在。