2

如果我在层次结构的基类中创建一个静态 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,这是不可取的。

4

3 回答 3

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
于 2012-10-12T05:08:29.010 回答
3

不,它是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;
}
于 2012-10-12T04:47:11.167 回答
0

您必须在构造函数成员初始化列表中初始化 const memember 变量。

你不能修改 const 变量。

于 2012-10-12T04:47:07.500 回答