为何CaesarText类无法继承父类ShiftText的无参decrypt方法?
问题:CaesarText无法继承ShiftText的无参decrypt方法?
问题背景
ShiftText类支持自定义密钥的移位加密解密,CaesarText继承自ShiftText,固定密钥为3。但调用msg.decrypt()时触发错误,提示CaesarText::decrypt不接受0个参数。
ShiftText.h 代码
class ShiftText : public PlainText { protected: int key; public: ShiftText(string text, int key); ~ShiftText(); static string encrypt(string text, int key); static string decrypt(string text, int key); string encrypt(); string decrypt(); };
CaesarText.h 代码
class CaesarText : public ShiftText { public: CaesarText(string text); ~CaesarText(); // hiding the previous methods of the ShiftText class static string encrypt(string text); static string decrypt(string text); };
报错的调用代码
PlainText Bob(CaesarText msg) { cout << endl << "Bob:" << endl; cout << "The received message: " << msg.getText() << endl; cout << "The decrypted message is: " << msg.decrypt() << endl; return PlainText("Many Thanks Alice!"); }
错误信息
'CaesarText::decrypt': function does not take 0 arguments
原因分析
你在CaesarText中声明了同名的静态decrypt方法(接受1个参数),这会直接隐藏父类ShiftText中所有同名的decrypt方法(包括无参的实例方法)。C++的规则是:当子类声明了与父类同名的函数(不管参数列表是否不同),父类的同名函数会被隐藏,而非重载。
解决方案
有两种实用的解决方式:
方式1:显式引入父类方法
在CaesarText的public区域添加using ShiftText::decrypt;,让父类的无参decrypt方法在子类中重新可见:
class CaesarText : public ShiftText { public: CaesarText(string text); ~CaesarText(); using ShiftText::decrypt; // 引入父类的无参decrypt方法 using ShiftText::encrypt; // 若需要父类无参encrypt也可同步引入 static string encrypt(string text); static string decrypt(string text); };
方式2:子类重写无参decrypt方法
既然CaesarText固定密钥为3,也可以直接在子类中实现无参decrypt,内部复用父类逻辑:
class CaesarText : public ShiftText { public: CaesarText(string text) : ShiftText(text, 3) {} // 构造时传入固定密钥3 ~CaesarText(); static string encrypt(string text); static string decrypt(string text); // 重写无参decrypt方法 string decrypt() { return ShiftText::decrypt(); // 调用父类的无参解密逻辑 } };
注意:CaesarText的构造函数必须正确调用父类ShiftText的构造函数并传入固定密钥3,这样父类的key成员才能被正确初始化,保证无参decrypt方法能正常工作。
内容的提问来源于stack exchange,提问作者Useless Fish
相关产品推荐
相关产品推荐

