Re: static variables in g++
coderyogi wrote:
The problem statement is to print the numbers from 1 to 100 and then
back to 1; without using
a) recursion
b) any loops
I've coded the solution as follows:
[CODE]
#include <iostream.h>
class list {
private:
static int count;
public:
list ()
{
cout << ++count << endl;
}
~list ()
{
cout << count-- << endl;
}
};
int main (void)
{
list a[100];
return 0;
}
[/CODE]
Although the code gives correct output with turbo c compiler, i get
following errors with g++:
/tmp/ccJCckwR.o(.list::gnu.linkonce.t.(void)+0x16): In function
`list::list(void)':
: undefined reference to `list::count'
/tmp/ccJCckwR.o(.list::gnu.linkonce.t.(void)+0x1c): In function
`list::list(void)':
: undefined reference to `list::count'
/tmp/ccJCckwR.o(.gnu.linkonce.t._._4list+0x17): In function
`list::~list(void)':: undefined reference to `list::count'
/tmp/ccJCckwR.o(.gnu.linkonce.t._._4list+0x1d): In function
`list::~list(void)':: undefined reference to `list::count'
collect2: ld returned 1 exit status
If anybody can help, thanx!
Interesting problem :-) Other people have pointed out what the issue
with your solution was, so I won't repeat that, but FWIW you can also do
it like this:
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
using boost::lexical_cast;
template <int N> struct Up : Up<N-1> {
static std::string s;
Up() { s = Up<N-1>::s + lexical_cast<std::string,int>(N) + " "; }
};
template <> struct Up<0> {
static std::string s;
Up() { s = ""; }
};
template <int N> struct Down : Down<N-1> {
static std::string s;
Down() { s = lexical_cast<std::string,int>(N) + " " + Down<N-1>::s; }
};
template <> struct Down<0> {
static std::string s;
Down() { s = ""; }
};
template <int N> std::string Up<N>::s;
std::string Up<0>::s;
template <int N> std::string Down<N>::s;
std::string Down<0>::s;
int main()
{
std::cout << Up<100>().s << Down<99>().s << std::endl;
return 0;
}
I suppose it's arguable whether or not it uses recursion (in some sense
of the word), but it certainly doesn't do it explicitly. Nor does it use
any loops.
Cheers,
Stu
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]