Why are classes with static data members getting linker errors?__ language Basics

Source: Internet
Author: User

Http://www.parashift.com/c++-faq-lite/link-errs-static-data-mems.html


Because static data members must is explicitly defined in exactly one compilation. If you are didn ' t do this and you'll probably get a "undefined external" linker error. For example:

Fred.h

class Fred {public
:
  ...
Private:
  static int j_;   Declares static data member Fred::j_ ...
};
The linker would holler at your ("Fred::j_ is not defined") unless your define (as opposed to merely declare) fred::j_ in ( Exactly) one of your source files:
Fred.cpp

#include "Fred.h"

int fred::j_ = some_expression_evaluating_to_an_int;

Alternatively, if you wish the implicit 0 value for static ints:
//int fred::j_;
The usual place to define static data members of class Fred is file Fred.cpp (or fred.c or whatever source file Exten Sion use).

Note:in some cases, you can add = initializer; To the declaration of Class-scope static declarations, however if your ever use the ' data ', you still need to explicit Ly define it in exactly one compilation. In this case you don ' t include a = initializer in the definition. A separate FAQ covers this topic.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.