简体   繁体   中英

How to initial “static const char * []” in class member?[C++]

When I am doing my homework, the question ask me to finish the given class:

//Card.hpp
class Card {
private:
    static const char* faceNames[totalFaces];
};

I write mycode in Card.cpp :

const char* faceNames[Card::totalFaces] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };

I use VS2017 to build it, but it shows that

error LNK2001: unresolved external symbol "private: static char const * * Card::faceNames" (?faceNames@Card@@0PAPBDA)

How should I do?

You can define it outside the class without specifying the size. You don't have to specify the size again. Note the :: requirement for defining members outside class.

const char* Card::faceNames[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };

Demo

You accidentally defined an unrelated array faceNames when you meant to define the static member. You need to name the class static member using :: notation:

const char* Card::faceNames[Card::totalFaces] = { "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM