抱歉,如果这是重复的。
这是我无法理解的有关静态指针类成员的示例代码片段。
#include <iostream>
class MyField {
public:
MyField() { std::cout << "ctr for MyField\n"; }
~MyField() { std::cout << "dtr for MyField\n"; }
friend std::ostream &operator<<(std::ostream &os, MyField field) {
os << "dump for MyField with addr: " << &field << std::endl;
return os;
}
};
class MyClass {
private:
static MyField field_;
public:
static MyField *p_field_;
static void setField(MyField const &field) { field_ = field; }
static void setPField(MyField *p_field) { p_field_ = p_field; }
static void dumpField() { std::cerr << "field_: " << field_; }
static void dumpPField() { std::cerr << "p_field_: " << *p_field_; }
MyClass() { std::cout << "ctr for MyClass\n"; }
~MyClass() { std::cout << "dtr for MyClass\n"; }
};
int main(void) {
MyClass::setPField(NULL); /// undefined reference to MyClass::p_field_
MyClass::p_field_ = NULL; /// undefined reference to MyClass::p_field_
MyField field;
MyClass::setField(field); /// fine
MyClass::p_field_ = &field; /// undefined reference to MyClass::p_field_
MyClass::setPField(&field); /// undefined reference to MyClass::p_field_
MyClass();
MyClass::dumpField(); /// fine
MyClass::dumpPField(); /// fine
return 0;
}
对于类
MyClass
,为什么字段field_
(setField)的集合有效,但对于p_field_
(setPField)却无效?而且它仍然可以访问p_field_
(dumpPField)的地址吗?顺便说一句,我尝试了gcc4.8 / clang3.4,是否带有
--std=c++11
。 最佳答案
加:
MyField * MyClass::p_field_ = NULL;
任何功能之外的功能,例如就在
int main() {
之前关于c++ - C++中静态指针类成员的链接期间 undefined reference ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24970540/