您應該能夠使用公共存取函數:
Derived& Derived::operator=(const Derived& rhs)
{
if (&rhs != this)
SetColour(rhs.GetColour());
return *this;
}
以其他方式在基類保護的成員,使派生類訪問:
Derived& Derived::operator=(const Derived& rhs)
{
if (&rhs != this)
colour = rhs.colour;
return *this;
}
第三個選擇可能是在基類中定義一個賦值運算符公衆和你的派生類中調用基操作:
Derived& Derived::operator=(const Derived& rhs)
{
if (&rhs != this)
Base::operator=(rhs);
return *this;
}
下面是一個完整的測試用例:
#define TEST 2
class Base
{
public:
Base() : m_protected(0), m_private(0) {}
Base(int pro, int pri) : m_protected(pro), m_private(pri) {}
~Base() {}
#if TEST == 1
Base& operator=(const Base& rhs)
{
if (this != &rhs)
{
m_protected = rhs.m_protected;
m_private = rhs.m_private;
}
return *this;
}
#elif TEST == 2
void SetPrivate(int i) { m_private = i; }
int GetPrivate() const { return m_private; }
#endif
protected:
int m_protected;
private:
int m_private;
};
class Derived : public Base
{
public:
Derived() : Base() {}
Derived(int pro, int pri) : Base(pro, pri) {}
#if TEST == 1
Derived& operator=(const Derived& rhs)
{
Base::operator=(rhs);
return *this;
}
#elif TEST == 2
Derived& operator=(const Derived& rhs)
{
if (this != &rhs)
{
SetPrivate(rhs.GetPrivate());
m_protected = rhs.m_protected;
}
return *this;
}
#endif
};
int main()
{
Derived a;
Derived b(10, 5);
a = b;
return 0;
}
你確定嗎?我的編譯器不允許我從基類,公共或其他地方訪問任何東西。 – SirYakalot
它表示沒有重載參數的實例匹配(這不是真的)並且還說對象具有阻止匹配的類型限定符。那是什麼意思? – SirYakalot
所有這些工作如果您使用公共繼承和非const方法。你能否展示更多的類定義和用法? – AJG85