我在C++中有两个类,其中一个继承自另一个:
class A {
public:
virtual void Initialize(){
m_MyString = "Default value";
}
protected:
string m_MyString;
}
class B : public A {
public:
void Initialize(){
A::Initialize();
m_MyString = "New Value";
}
}
上述B类与这一类之间有区别吗?
class B : public A {
public:
void Initialize(){
A::Initialize();
A::m_MyString = "New Value";
}
}
似乎使用作用域运算符会导致字符串中有垃圾,对吗?我在想,当它覆盖时,A::m_MyString与B::m_MyString不同。这有道理吗?
我看到变量在A中设置,然后当我们返回到B时,出现了垃圾。这与“隐藏”与“覆盖”有关吗?
最佳答案
您的代码在许多方面无效。它应该看起来像:
class A { // << errors were here
public:
virtual void Initialize(){
m_MyString = "Default value";
}
protected:
string m_MyString;
}; // << lost ;
class B : public A // << errors were here
{
public:
virtual void Initialize(){ // << virtual
A::Initialize(); // has no effect in the end
A::m_MyString = "New Value"; // same as `m_MyString = "New Value";`
}
}; // << lost ;
在上面的代码中,
m_MyString
没有区别。发布您的实际代码并显示错误。如果您的代码如下所示:
class B : public A
{
public:
virtual void Initialize(){
// here is a difference
A::m_MyString = "New Value";
m_MyString = "New Value";
}
protected:
string m_MyString; // !!! overridden
};
然后就不同了,因为
B
有m_MyString
的两个实例:A::m_MyString
和B::m_MyString
。关于c++ - 继承时的变量作用域,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1682281/