如果我在层次结构的基类中创建静态常量,我可以在派生类中重新定义它的值吗?在派生类中重新定义静态常量值C++
编辑:
#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
指Base::i
,这是不可取的。
编辑(由OP)已经改变了这个问题_a lot_。它现在使用原始问题的答案的源代码来创建一个全新的答案,这实际上是使用指针访问静态成员。 – jogojapan