我正在学习ns-3 tutorial 。我无法理解以下代码片段:
class MyObject : public Object
{
public:
static TypeId GetTypeId (void)
{
static TypeId tid = TypeId ("MyObject")
.SetParent (Object::GetTypeId ())
.AddConstructor<MyObject> ()
.AddTraceSource ("MyInteger",
"An integer value to trace.",
MakeTraceSourceAccessor (&MyObject::m_myInt))
;
return tid;
}
MyObject () {}
TracedValue<int32_t> m_myInt;
};
据我了解,MyObject::m_myInt 是从静态方法对非静态类成员 m_myInt 的访问,并且 & 获取该成员的地址。这段代码已成功编译并执行。怎么可能?静态方法使用什么类实例?
最佳答案
指向成员的指针可以是指向成员方法或成员变量的指针,并且不需要声明或分配类的实例。然而,这并不意味着您可以在没有实例的情况下做很多事情。您仍然需要一个实例来使用它们。考虑以下代码:
class A
{
public:
void SomeMethod();
int someVar;
};
void (A::*pSomeMethod)() = &A::SomeMethod; //Declares a member pointer to method and assigns
int A::*pSomeVar = &A::someVar; //Declares a member pointer to int variable and assigns
A a; //Defines an instance
(a.*pSomeMethod)(); //Uses an instance with the pSomeMethod member pointer.
int var = (a.*pSomeVar); //Uses an instance with the pSomeVar member pointer.
这是可能的,并且它允许一些非常酷的东西。
关于c++ - 从静态方法访问非静态成员的工作示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11694870/