多重继承的弊端
解决方案一:
使用"类名"::进行指定, 指定调用从哪个基类继承的方法!!!
wsc.Father::dance();
wsc.Mother::dance();
解决方案二:
在子类中重新实现这个同名方法, 并在这个方法内部, 使用基类名进行限定,
来调用对应的基类方法.
void Son::dance()
{
Father::dance();
Mother::dance();
cout << "街舞" << endl;
}
不BB直接上代码:
第一个类: Father(老爸)
第二个类: Mother(老妈)
第三个类: Son(儿子)
Father.h
#pragma once
#include <string>
using namespace std;
class Father
{
public:
Father(const char* lastName = "无名", const char* firstName = "无名");
~Father();
void playBasketball(); /* 打篮球 */
void dance(); /* 跳舞 */
private:
string lastName; /* 姓 */
string firstName; /* 名 */
};
Father.cpp
#include "Father.h"
#include <iostream>
Father::Father(const char* lastName, const char* firstName)
{
this->lastName = lastName;
this->firstName = firstName;
}
Father::~Father()
{
}
void Father::playBasketball()
{
cout << "我要三步上篮了!" << endl;
}
void Father::dance()
{
cout << "我要跳霹雳舞" << endl;
}
Mother.h
#pragma once
#include <string>
using namespace std;
class Mother
{
public:
Mother(const char* food,
const char* lastName = "无姓", const char* firstName = "无名");
~Mother();
void dance();
private:
string lastName; /* 姓 */
string firstName; /* 名 */
string food; /* 喜欢的食物 */
};
Mother.cpp
#include "Mother.h"
#include <iostream>
using namespace std;
Mother::Mother(const char* food, const char* lastName, const char* firstName)
{
this->food = food;
this->lastName = lastName;
this->firstName = firstName;
}
Mother::~Mother()
{
}
void Mother::dance()
{
cout << "跳舞擦擦" << endl;
}
Son.h
#pragma once
#include "Mother.h"
#include "Father.h"
class Son :public Father, public Mother
{
public:
Son(const char* lastName, const char* firstName,
const char* food,
const char* game);
~Son();
void playGame();
void dance();
private:
string game;
};
Son.cpp
#include "Son.h"
#include <iostream>
using namespace std;
Son::Son(const char* lastName, const char* firstName,
const char* food, const char* game):Father(lastName,firstName),Mother(food)
{
this->game = game;
}
Son::~Son()
{
}
void Son::playGame()
{
cout << "一起玩" << game << endl;
}
void Son::dance()
{
Father::dance();
Mother::dance();
cout << "街舞" << endl;
}
main
#include "Father.h"
#include "Mother.h"
#include "Son.h"
int main()
{
Son wsc("王", "思聪", "粤菜", "王者");
wsc.playBasketball();
wsc.dance();
wsc.playGame();
wsc.Father::dance();
wsc.Mother::dance();
wsc.dance();
system("pause");
return 0;
}
运行环境: vs2019
运行结果:
结语:
学到的知识要, 多复习, 多总结, 多敲. 需要时间的积累, 才能引起质的改变. 自己写不出来的永远是别人的.
分享一下我的技巧: 代数法把具体的数字带进去, 看看能能能找到规律(掌握思想).
还有就是画图, 也很重要. 用笔画出来, 把数代进去, 方法虽然笨, 但真的很实用, 好记忆不如烂笔头!!!
我是小白, 如果存在问题, 欢迎大神给予评判指正.
错了不可怕, 可怕的是找不出bug
今日是: 2020年5月2日, (由于疫情的原因)在家里整天坐在电脑前, 眼神逐渐从大到小, 视力也有所大大的下降 ,中午期待打篮球. 写博客, 就当写写日记吧!!!,
希望给个赞: 反正你又不亏, 顺便而已