2012-10-12 57 views
3

如果我在层次结构的基类中创建静态常量,我可以在派生类中重新定义它的值吗?在派生类中重新定义静态常量值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; 
} 

... ptrBase::i,这是不可取的。

+2

编辑(由OP)已经改变了这个问题_a lot_。它现在使用原始问题的答案的源代码来创建一个全新的答案,这实际上是使用指针访问静态成员。 – jogojapan

回答

4

访问静态成员是通过其声明类型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 
0

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

你不能修改const变量。

+1

记住这个问题是关于一个静态成员。 – jogojapan

2

不是,这是const,所以你不能修改它的值。

但是你可以为派生类声明一个新名称为static const的相同名称,并在那里定义它的值。经由ptr

#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; 
} 
+0

const_cast呢? –

+0

@Xploit是的,没错。当然'const_cast'可以让你修改这个值。即使没有派生类时也是如此。 – jogojapan

+0

请注意,Base中的成员fns将继续访问基本的静态常量,但也有解决方法。 – WhozCraig

相关问题