data member inside a class can be const but only if its static. otherwise we 开发者_高级运维need to have a constructor to initialize a constant inside a class.
can we declare a const data member inside a class? //this was an interview question
It seems to me that we can, but is it appropriate for a programmer to declare a constant inside a class.
please give some explanation/reasons, why we can or cannot do?
Off course you can :
struct A
{
A() : a(5)
{
}
const int a;
};
int main()
{
A a;
}
This means that the data member a, inside struct A is not going to change.
Short answer : You can have a non-static const
member inside a class.
As you still need to assign it a value, the only place where you're allowed to is in the initialization list.
And, well, it's always a good reason to do it if your member is really constant. I mean, const-correctness is mainly an optional tool to help better coding, so use it if you want, you'll thank yourself later. And if you don't use it... well it doesn't really matter!
sure if you have some constants you want to use in your class, and belong to a class.
For example, lets say you have some data type with a unique ID, the ID identifies the object an therefor will never change:
class myData {
cont int ID;
myData(int newID) : ID(newID) {}
}
精彩评论