473,658 Members | 2,628 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how do you declare and use a static constant array inside a class

Hi all,

I would like to have a static constant array inside a class definition
which would contain the number of days in each month (I am writing a
Date class as an exercise). However my attempts so far have been
unsuccessful.

Take this Test class as an example

// test.hpp
#include <ostream>
#include <string>
using namespace std;

#ifndef TEST_HPP
#define TEST_HPP

class Test
{
public:
static const int arr[]= {1,2,3}; // LINE 11
Test(string n);
friend ostream& operator<<(ostr eam& o, const Test& test);
private:
string name;
};

#endif

// test.cpp
#include "test.hpp"

Test::Test(stri ng n)
{
name= n;
}

ostream& operator<<(ostr eam& o, const Test& test)
{
o << test.name << " " << Test::arr[0] << endl; // LINE 10
}

When I compile this I get the following errors (see the comments for
the line numbers);

test.hpp:11: error: a brace enclosed initializer is not allowed here
before the '{' token
test.hpp:11: error: invalid in-class initialization of static data
member of a non-integral type 'const int[]'
test.cpp:10: 'arr' is not a member of 'Test'

However if I were to declare a static const int variable, set it's
value in the header file and use it on line 10 in the same way I would
not get any problems;

replace LINE 11 in test.hpp with;

static const int a=0;

replace LINE 10 in test.cpp with;

o << test.name << " " << Test::a << endl;

So how should I declare a static constant array in the class and how
should I dereference it in functions outwith the class?

John

Mar 28 '07 #1
3 20867
* johnmmcparland:
Hi all,

I would like to have a static constant array inside a class definition
which would contain the number of days in each month (I am writing a
Date class as an exercise). However my attempts so far have been
unsuccessful.

Take this Test class as an example

// test.hpp
#include <ostream>
#include <string>
using namespace std;
It's not a good idea to put 'using namespace std;' in a header file.

#ifndef TEST_HPP
#define TEST_HPP
Include guard should be the very first (non-comment) in the file, just
as a matter of principle (e.g., avoid having the compiler needlessly
parse other includes).

class Test
{
public:
static const int arr[]= {1,2,3}; // LINE 11
You can declare it here, but you can't initialize it here.

Initialize it in a separate definition.
Test(string n);
friend ostream& operator<<(ostr eam& o, const Test& test);
private:
string name;
};

#endif
Since it seems you're placing all your code in headers (the hpp
extension implies a header file with all implementation code) the
easiest for you is probably to use a static constant in a member
function, like

class Test
{
private:
static char const* const* monthNames()
{
static char const* rawNames[] = { "jan", "feb", ... };
}
public:
...
};
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Mar 28 '07 #2
On 28 Mar, 14:04, "Alf P. Steinbach" <a...@start.now rote:
*johnmmcparland :
Hi all,
I would like to have a static constant array inside a class definition
which would contain the number of days in each month (I am writing a
Date class as an exercise). However my attempts so far have been
unsuccessful.

Take this Test class as an example
// test.hpp
#include <ostream>
#include <string>
using namespace std;

It's not a good idea to put 'using namespace std;' in a header file.
#ifndef TEST_HPP
#define TEST_HPP

Include guard should be the very first (non-comment) in the file, just
as a matter of principle (e.g., avoid having the compiler needlessly
parse other includes).
class Test
{
public:
static const int arr[]= {1,2,3}; // LINE 11

You can declare it here, but you can't initialize it here.

Initialize it in a separate definition.
Test(string n);
friend ostream& operator<<(ostr eam& o, const Test& test);
private:
string name;
};
#endif

Since it seems you're placing all your code in headers (the hpp
extension implies a header file with all implementation code) the
easiest for you is probably to use a static constant in a member
function, like

class Test
{
private:
static char const* const* monthNames()
{
static char const* rawNames[] = { "jan", "feb", ... };
}
public:
...
};

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Ok I take on board what you said about hpp (I thought it was only a
way to distinguish between C++ headers and C headers) using namespace
std; and the #defines.

Regarding;
class Test
{
public:
static const int arr[]= {1,2,3}; // LINE 11
You can declare it here, but you can't initialize it here.
Initialize it in a separate definition.
I don't know what you mean. Declaring it (static const int arr[12];)
then initializing in the header doesn't work either. And I don't like
the idea of doing it in the function. It adds an unnecessary layer of
abstraction.

How should i declare and initialize this array?

Mar 29 '07 #3
On 29 Mar, 10:37, "johnmmcparland " <johnmmcparl... @googlemail.com >
wrote:
On 28 Mar, 14:04, "Alf P. Steinbach" <a...@start.now rote:
*johnmmcparland :
class Test
{
public:
static const int arr[]= {1,2,3}; // LINE 11
You can declare it here, but you can't initialize it here.
Initialize it in a separate definition.

I don't know what you mean. Declaring it (static const int arr[12];)
then initializing in the header doesn't work either. And I don't like
the idea of doing it in the function. It adds an unnecessary layer of
abstraction.

How should i declare and initialize this array?
Header file:
class Test
{
public:
static const int arr[];
};

Implementation file:
const int Test::arr[3] = {1,2,3};

Gavin Deane

Mar 29 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2834
by: trying_to_learn | last post by:
I'm learning consts in C++ and the book says that u have to initialize non-static consts inside the constructor initializer list, however "const string* stack" isn't initialized in the constructor initializor list,instead its initialized inside the constructor main body using memset.I dont understand this,why isnt this uniform class StringStack { static const int size = 100; const string* stack; int index;
2
3582
by: Drew McCormack | last post by:
I am getting an error in g++ 4.0.0 that I did not get in g++ 3.4. I have a header with the following const variables with namespace scope: namespace Periphery { extern const double ProtonMassInAtomicUnits = 1836.152755656068; } I try to use these in another header to initialize static const member
14
2815
by: John Ratliff | last post by:
I'm trying to find out whether g++ has a bug or not. Wait, don't leave, it's a standard C++ question, I promise. This program will compile and link fine under mingw/g++ 3.4.2, but fails to link under Linux/g++ 3.3.3. --------------------------------------------- #include <iostream> #include <utility>
3
5509
by: Mark Dunmill | last post by:
I can't create a Constant/Read-only array field in managed C++ classes - doesn't allow the keyword const pointer to const object on array fields in managed C++ classes. e.g. Want to define a read/only field for an empty array (so all the empty arrays of the given type can use the same object) however because the pointer in the field cannot be marked as constant then it is possible that any external party can alter this pointer to reference...
15
5316
by: Geoff Cox | last post by:
Hello, Can I separately declare and initialize a string array? How and where would I do it in the code below? It was created using Visual C++ 2005 Express Beta 2 ... In C# I would have private string myArray;
6
30554
by: The8thSense | last post by:
how to declare static varible and static method inside a class ? i try "public static ABC as integer = 10" and it said my declaration is invalid Thanks
10
2646
by: stonny | last post by:
I read the following sentence from a c++ website, but can not understand why. can anyone help me with it? " An important detail to keep in mind when debugging or implementing a program using a static class member is that you cannot initialize the static class member inside of the class. In fact, if you decide to put your code in a header file, you cannot even initialize the static variable inside of the header file; do it in a .cpp file...
3
2664
by: Alexander Hans | last post by:
Hi, what's the usual way in C++ to define a static constant class member? Consider the following example: class TestClass { public: static const double a = 12.5; static const double b = 2 * a;
2
2475
by: Ranganath | last post by:
Hi, Why is there a restriction that only integral types can be made static constant members of a class? For e.g., class B { private: static const double K = 10; };
0
8330
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8850
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8746
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7355
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4334
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2749
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.