如果我在层次结构的基类中创建一个静态const,我可以在派生类中重新定义它的值吗?
编辑:
#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
,这是不受欢迎的。
答案 0 :(得分:4)
通过ptr
访问静态成员是通过其声明的类型Base *
而不是其运行时类型(有时是Base *
,有时是Derived *
)。您可以通过以下简单的程序扩展来看到这一点:
#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;
}
输出:
Base::i == 1
Derived::i == 2
b_ptr=1
d_ptr=2
答案 1 :(得分:2)
没有。它是const
,因此您无法修改其值。
但是你可以为派生类声明一个同名的新static const
,并在那里定义它的值。
#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;
}
答案 2 :(得分:0)
您必须在构造函数成员初始化列表中启动const成员变量。
你无法修改const变量。