在C ++中为静态指针类成员链接期间的未定义引用

时间:2014-07-26 11:27:48

标签: c++ static-methods static-members lifetime

很抱歉,如果这是重复的话 这是关于静态指针类成员我无法理解的一段示例代码。

#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 field_(setField)的集合有效,但p_field_(setPField)无效?它仍可用于访问p_field_(dumpPField)的地址?

BTW,我试过gcc4.8 / clang3.4,有或没有--std=c++11

1 个答案:

答案 0 :(得分:3)

添加:

MyField * MyClass::p_field_ = NULL;

在任何功能之外,例如就在int main() {

之前