C++:在 OBJ、OBJ&、const OBJ& 上调用时实现不同的方法

C++: Implement different methods when called on OBJ, OBJ&, const OBJ&

本文关键字:OBJ 实现 方法 const C++ 调用      更新时间:2023-10-16

有没有办法(我怀疑它涉及继承和多态性)来区分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 &&"。