If I create a static const in the base class of my hierarchy, can I redefine its value in a derived class?
edit:
#include <iostream>
class Base
{
public:
static const int i = 1;
};
class Derived : public Base
{
public:
static const int i = 2;
};
int main()
{
std::cout << "Base::i == " << Base::i << std::endl;
std::cout << "Derived::i == " << Derived::i << std::endl;
Base * ptr;
ptr= new Derived;
std::cout<< "ptr=" << ptr->i << std::endl;
return 0;
}
... ptr
refers to Base::i
, which is undesirable.
Access via ptr
to static members is via its declared type Base *
and not its runtime type (sometimes Base *
, sometimes Derived *
). You can see this with the following trivial extension of your program:
#include <iostream>
class Base
{
public:
static const int i = 1;
};
class Derived : public Base
{
public:
static const int i = 2;
};
int main()
{
std::cout << "Base::i == " << Base::i << std::endl;
std::cout << "Derived::i == " << Derived::i << std::endl;
Base *b_ptr = new Derived;
std::cout<< "b_ptr=" << b_ptr->i << std::endl;
Derived *d_ptr = new Derived;
std::cout<< "d_ptr=" << d_ptr->i << std::endl;
return 0;
}
Output:
Base::i == 1
Derived::i == 2
b_ptr=1
d_ptr=2
No. It's const
, so you cannot modify its value.
But you can declare a new static const
of the same name for the derived class, and define its value there.
#include <iostream>
class Base
{
public:
static const int i = 1;
};
class Derived : public Base
{
public:
static const int i = 2;
};
int main()
{
std::cout << "Base::i == " << Base::i << std::endl;
std::cout << "Derived::i == " << Derived::i << std::endl;
return 0;
}
you must initiate the const memember variable in the Constructor member initialization list.
you can not modify the const variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.