J
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;
#ifndef TEST_HPP
#define TEST_HPP
class Test
{
public:
static const int arr[]= {1,2,3}; // LINE 11
Test(string n);
friend ostream& operator<<(ostream& o, const Test& test);
private:
string name;
};
#endif
// test.cpp
#include "test.hpp"
Test::Test(string n)
{
name= n;
}
ostream& operator<<(ostream& 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
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<<(ostream& o, const Test& test);
private:
string name;
};
#endif
// test.cpp
#include "test.hpp"
Test::Test(string n)
{
name= n;
}
ostream& operator<<(ostream& 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