C++:在 OBJ、OBJ&、const OBJ& 上调用时实现不同的方法
C++: Implement different methods when called on OBJ, OBJ&, const OBJ&
有没有办法(我怀疑它涉及继承和多态性)来区分OBJ o, OBJ& o, const OBJ& o
?我希望在 3 个不同的程序中使用相同的代码,并使用相同的方法名称调用不同的方法。
int main(){
try{
// try something
}catch(OBJ o){
o.doSomething(); // Do action 1
}
return 0;
}
int main(){
try{
// try something
}catch(OBJ& o){
o.doSomething(); // Do action 2
}
return 0;
}
int main(){
try{
// try something
}catch(const OBJ& o){
o.doSomething(); // Do action 3
}
return 0
}
是的,通过多态性,你可以使具有相同标头(声明)的函数采用不同的形式(这就是这个词的意思 - polys,"很多,很多"和morphe,"form,shape">),在我们的例子中,执行不同的指令。当然,该函数必须是两个类的方法,其中一个类继承另一个类。每个类都应根据需要实现该功能。此外,您将对基类的引用实际上引用派生类的对象(poly morphe -相同的事物,多种形式),从而获得所需的行为。
请考虑以下代码:
class BaseClass{
public:
virtual void call() const { cout<<"I am const function 'call' from BaseClassn"; };
virtual void call() { cout<<"I am function 'call' from BaseClassn"; }
};
class DerivedClass1: public BaseClass{
public:
void call() { cout<<"I am function 'call' from DerivedClass1n"; }
};
class DerivedClass2: public BaseClass{
public:
void call() const { cout<<"I am const function 'call' from DerivedClass2n"; }
};
int main()
{
BaseClass b;
DerivedClass1 d1;
DerivedClass2 d2;
try{
throw b;
}
catch (BaseClass ex){
ex.call();
}
try{
throw d1;
}
catch (BaseClass& ex){
ex.call();
}
try{
throw d2;
}
catch (const BaseClass& ex){
ex.call();
}
return 0;
}
输出将是:
我是来自基类的函数"调用" 我是来自衍生类 1 的函数"调用" 我是来自 DerivedClass2 的常量函数"调用">
请注意,BaseClass 中有 2 个虚函数,因为
void call() const
不同于
void call()
您可以在此处阅读有关多态性的更多信息:
https://www.geeksforgeeks.org/virtual-functions-and-runtime-polymorphism-in-c-set-1-introduction/
你可以让成员调用左值引用和右值引用之间的区别,但是如果你有一个"void member() const &",你不能有一个普通的"void member() const",但是你可以有一个"void member() const &&"。
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- C++:在 OBJ、OBJ&、const OBJ& 上调用时实现不同的方法
- 如何实现 <Obj>Cython 的向量<向量>(C++ 到 Python)?
- 是否有任何现有的库在C/CPP/Obj-C中实现matlab函数
- “delete[] obj”和“delete obj”是如何在编译器级别实现的