I get the error error: ‘Name’ was not declared in this scope
What am I missing here.
Source File:
#include<iostream>
#include "scr.h"
using namesp开发者_如何学Cace std;
const char* const Test::Name;
void Test::Print()
{
cout<<Name;
}
int main()
{
Test *t = new Test();
t->Print();
delete t;
}
Header File:
class Test
{
static const char* const Name = "Product Name";
public:
void Print();
};
EDIT:
If I replace char* const
with int
, it works. Why?
static const int Name = 4; //in header
const int Test::Name; //In source
The purpose of the code is to have an alternate for #define
as mentioned in Effective C++. In the example there, static const int
is used.
You cannot initialize a static member variable within a class. Not even in the header file.
Header File:
class Test
{
static const char* const Name;
public:
void Print();
};
In your cpp file:
const char* const Test::Name = "Product Name";
Edit: I must have added that the initialization is allowed only for int and enumerations and that too with constants that can be evaluated at compile time.
You can't initialize
members in class definition.
Take a look at Parashift post - Can I add = initializer; to the declaration of a class-scope static const data member?
SUMMARY: The caveats are that you may do this only with
integral
orenumeration
types, and that the initializer expression must be an expression that can be evaluated at compile-time: it must only contain other constants, possibly combined with built-in operators.
In general, you can't initialize static variables directly in the class definition, you have to do it in a separate source file, like this:
const char* const Test::Name = "Product Name";
An exception is integral constants, which are allowed to be in the class definition. An easy workaround is to use a static member function instead:
struct Test {
static const char *Name() { return "Product Name"; }
};
Move the assignment of the string to the source/implementation file (.cpp).
精彩评论