Re: Some questions about macro and function design
Erik Wikstr=F6m wrote:
On 7 Mar, 08:59, "mimi" <cainiaodelixi...@gmail.com> wrote:
1.Instead of using macro, I would like to use static const variables
in such situations.
class Foo {
public:
static const int SOMEVALUEWITHFOO = 1;
}
int main()
{
Foo test;
return 0;
}
My first question is: Is using static const variables instead of macro
appreciated?
Yes, very much.
2. How to define a global variable which is initialized by the
parameter of main, and gurantee its constness by technology?
Take the program in question 1 for example.If I want SOMEVALUEWITHFOO
to be initialized by the parameters of main, and its value should
never be changed, and every object of Foo has the same value of
SOMEVALUEWITHFOO, how should I design the program?
Don't know if this is possible, if all classes should share the value
it has to be a static member, if it has to be unchangeable it has to
be const. Since it's static it's initialized before main is run and
since it's const it can't be changed after.
It might be possible to make something like a singleton, where you
have a static non-const variable and only use a method to access it,
but I don't know.
like this?
#include <stdexcept>
#include <iostream>
class Constant
{
public:
static int value() {return value_;}
private:
Constant() {}
~Constant() {}
static void setValue(int n) {value_ = n;}
static int value_;
friend class Setter;
};
class Setter
{
public:
static Setter* instance()
{
if (!instance_)
{
instance_ = new Setter();
return instance_;
}
std::cerr << "re-instantiating Setter" << std::endl;
throw std::logic_error("re-instantiating Setter");
return 0;
}
static void set (int n) {Constant::setValue(n);}
private:
static Setter* instance_;
};
Setter* Setter::instance_ = 0;
int Constant::value_ = 0;
void good()
{
std::cout << Constant::value() << std::endl;
}
void bad()
{
Setter::instance()->set(2);
std::cout << Constant::value() << std::endl;
}
int main()
{
Setter::instance()->set(1);
good();
bad();
return 0;
}
--
Nick Keighley