1、父子间的赋值兼容
#include <iostream>
#include <string>
using namespace std;
class Parent
{
public:
int mi;
void add(int i)
{
mi += i;
}
void add(int a, int b)
{
mi += (a + b);
}
};
class Child : public Parent
{
public:
int mv;
void add(int x, int y, int z)
{
mv += (x + y + z);
}
};
int main()
{
Parent p;
Child c;
p = c;
Parent p1(c);
Parent& rp = c;
Parent* pp = &c;
rp.mi = 100;
rp.add(5); // 没有发生同名覆盖?
rp.add(10, 10); // 没有发生同名覆盖?
/* 为什么编译不过? 编译器未找到*/
// pp->mv = 1000;
// pp->add(1, 10, 100);
return 0;
}
hellp.cpp:51:10: error: ‘class Parent’ has no member named ‘mv’
pp->mv = 1000;
^
hellp.cpp:52:24: error: no matching function for call to ‘Parent::add(int, int, int)’
pp->add(1, 10, 100);
2、
Parent& rp = c;
Parent* pp = &c;
所以rp 和pp只能访问父类成员和函数
3、特殊的同名函数(重写override)
4、思考
#include <iostream>
#include <string>
using namespace std;
class Parent
{
public:
int mi;
void add(int i)
{
mi += i;
}
void add(int a, int b)
{
mi += (a + b);
}
void print()
{
cout << "I'm Parent." << endl;
}
};
class Child : public Parent
{
public:
int mv;
void add(int x, int y, int z)
{
mv += (x + y + z);
}
void print()
{
cout << "I'm Child." << endl;
}
};
void how_to_print(Parent* p)
{
p->print();
}
int main()
{
Parent p;
Child c;
how_to_print(&p); // Expected to print: I'm Parent.
how_to_print(&c); // Expected to print: I'm Child.
return 0;
}
I'm Parent.
I'm Parent.
5、
6、
7、思考
合理,不是自己期望的结果