加法用算符重载
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
//1、 成员函数重载+号
Person operator+(Person &p)
{
Person temp;
temp.m_A = this->m_A + p.m_A;
temp.m_B = this->m_B + p.m_B;
return temp;
}
int m_A;
int m_B;
};
void test02()
{
Person p1;
p1.m_A = 10;
p1.m_B = 10;
Person p2;
p2.m_A = 10;
p2.m_B = 10;
Person p3 = p1 + p2;
cout << "p3.m_A = " << p3.m_A << endl;
cout << "p4.m_B = " << p3.m_B << endl;
}
int main(void)
{
test02();
system("pause");
return 0;
}
//2 全局函数重载+号
Person operator+(Person &p1, Person &p2)
{
Person temp;
temp.m_A = p1.m_A + p2.m_A;
temp.m_B = p1.m_B + p2.m_B;
return temp;
}
用法符重载也可以发生函数重载
继承的时候如果出现重名,那么就会使用自身类中的
当然父类中的的也是可以进行访问的,但是需要加入父类的作用域。
#include<iostream>
#include<string>
using namespace std;
class Father
{
public:
int m_A = 100;
int m_B = 120;
void show()
{
cout << "this is father!" << endl;
}
};
class Son:public Father
{
public:
int m_A = 200;
int m_B = 180;
void show()
{
cout << "this is son!" << endl;
}
};
void test01()
{
Son p1;
p1.m_A;
cout << "p1.m_A = " << p1.Father::m_A << endl;
p1.Father::show();
}
int main(void)
{
test01();
system("pause");
return 0;
}
继承中同名静态成员处理方式
//继承中的同名静态成员处理方式
静态变量,类内要声明,类外要初始化
1>------ 已启动生成: 项目: Project20, 配置: Debug Win32 ------
1> 源.cpp
1>f:\c++\project20\project20\源.cpp(28): warning C4101: “s”: 未引用的局部变量
1> Project20.vcxproj -> F:\c++\Project20\Debug\Project20.exe
========== 生成: 成功 1 个,失败 0 个,最新 0 个,跳过 0 个 ==========
多继承语法
实际开发中一般不用多继承
二义性
当父类中出现同名成员,需要加作用域区分。
总结:多继承中如果出现了同名情况,子类使用时候要加作用域。
利用虚继承 解决菱形的继承问题