Bạn sẽ có thể sử dụng accessors công cộng và mutators:
Derived& Derived::operator=(const Derived& rhs)
{
if (&rhs != this)
SetColour(rhs.GetColour());
return *this;
}
Nếu không làm cho các thành viên protected trong lớp cơ sở để các lớp thừa kế có quyền truy cập:
Derived& Derived::operator=(const Derived& rhs)
{
if (&rhs != this)
colour = rhs.colour;
return *this;
}
Tùy chọn thứ ba có thể là xác định toán tử gán công khai trong lớp cơ sở và yêu cầu lớp dẫn xuất của bạn gọi toán tử cơ sở:
Derived& Derived::operator=(const Derived& rhs)
{
if (&rhs != this)
Base::operator=(rhs);
return *this;
}
Dưới đây là một trường hợp thử nghiệm hoàn chỉnh:
#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;
}
bạn có chắc? trình biên dịch của tôi không cho phép tôi truy cập bất cứ thứ gì từ lớp cơ sở, công khai hay cách khác. – SirYakalot
nó nói không có trường hợp của các đối số quá tải phù hợp (đó là không đúng) và cũng nói rằng đối tượng có loại vòng loại mà ngăn chặn một trận đấu. Điều đó nghĩa là gì? – SirYakalot
Tất cả các công việc này nếu bạn đang sử dụng các phương thức thừa kế và không phải là công khai. Bạn có thể hiển thị nhiều định nghĩa và cách sử dụng lớp học của mình hơn không? – AJG85