65,210
社区成员
发帖
与我相关
我的任务
分享
A
(v)/ \(v)
B1 B2
\ /
(v) / \ (v)
C1 C2
\ /
D
#include <iostream>
struct A
{
A() : a(0)
{
}
A & operator = (const A & other)
{
if (&other == this) return (*this);
++a; // a = other.a;
std::cout << "A::operator = () !" << std::endl;
return (*this);
}
A & copy(const A & other) // 可以不用
{
// 什么也不做去做!
return (*this);
}
int a;
};
struct B1 : virtual public A
{
B1() : b1(0)
{
}
B1 & operator = (const B1 & other)
{
if (&other == this) return (*this);
A::operator = (other); // (菱形)最底层基类的的operator=
return (copy(other));
}
B1 & copy(const B1 & other)
{
if (&other == this) return (*this); // 1 -- 比较
A::copy(other); // 2 -- 直接基类的copy
++b1; // b1 == other.b1; // 3 -- 自身的修改
std::cout << "B1::operator = () !" << std::endl;
return (*this);
}
int b1;
};
struct B2 : virtual public A
{
B2() : b2(0)
{
}
B2 & operator = (const B2 & other)
{
if (&other == this) return (*this);
A::operator = (other); // (菱形)最底层基类的的operator=
return (copy(other));
}
B2 & copy(const B2 & other)
{
if (&other == this) return (*this); // 1 -- 比较
A::copy(other); // 2 -- 直接基类的copy
++b2; // b2 == other.b2; // 3 -- 自身的修改
std::cout << "B2::operator = () !" << std::endl;
return (*this);
}
int b2;
};
struct C : virtual public B1, virtual public B2
{
C() : c(0)
{
}
C & operator = (const C & other)
{
if (&other == this) return (*this);
A::operator = (other); // (菱形)最底层基类的的operator=
return (copy(other));
}
C & copy(const C & other)
{
if (&other == this) return (*this); // 1 -- 比较
B1::copy(other); // 2 -- 直接基类的copy
B2::copy(other); // 2 -- 直接基类的copy
++c; // c == other.c; // 自身的修改
std::cout << "C::operator = () !" << std::endl;
return (*this);
}
int c;
};
int main()
{
C cc;
std::cout << cc.a << " " << cc.b1 << " " << cc.b2 << " " << cc.c << std::endl;
std::cout << "-------------------" << std::endl;
cc = cc;
std::cout << "-------------------" << std::endl;
std::cout << cc.a << " " << cc.b1 << " " << cc.b2 << " " << cc.c << std::endl;
std::cout << "-------------------" << std::endl;
cc = C();
std::cout << "-------------------" << std::endl;
std::cout << cc.a << " " << cc.b1 << " " << cc.b2 << " " << cc.c << std::endl;
return 0;
}
#include <iostream>
using namespace std;
struct Person {
Person& operator=(Person&x) {std::cout << "Call Person's operator=!" << std::endl; return *this;}
};
struct Student : public virtual Person {
Student& operator=(Student& other) { std::cout << "Call Student's operator=!" << std::endl; return *this;}
};
struct Teacher : public virtual Person {
Teacher& operator=(Teacher& other) { std::cout << "Call Teacher's operator=!" << std::endl; return *this;}
};
struct Me : public Student, public Teacher {
Me& operator=(Me& other)
{
Person::operator=(*this);
Student::operator=(*this);
Teacher::operator=(*this);
std::cout << "Call Me's operator=!" << std::endl;
return *this;
}
};
int main ()
{
Me me;
me = me;
return 0;
}