gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:50:15 25 4
gpt4 key购买 nike

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

最佳答案

是的,通过多态性,您可以使具有相同 header (声明)的函数采用不同的形式(这就是这个词的意思 - polys,“很多,很多”和 morphe,“形式,形状”),在我们的例子中,执行不同的指令。当然,该函数必须是两个类的方法,其中一个继承另一个。每个类应根据需要实现功能。此外,您将对基类的引用实际上引用派生类的对象(多词形 - 同一事物,多种形式),从而获得所需的行为。

考虑以下代码:

class BaseClass{
public:
virtual void call() const { cout<<"I am const function 'call' from BaseClass\n"; };
virtual void call() { cout<<"I am function 'call' from BaseClass\n"; }
};

class DerivedClass1: public BaseClass{
public:
void call() { cout<<"I am function 'call' from DerivedClass1\n"; }
};

class DerivedClass2: public BaseClass{
public:
void call() const { cout<<"I am const function 'call' from DerivedClass2\n"; }
};

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;
}

输出将是:

I am function 'call' from BaseClassI am function 'call' from DerivedClass1I am const function 'call' from DerivedClass2

Notice that there are 2 virtual functions in the BaseClass, since

void call() const

不同于

void call()

您可以在此处阅读有关多态性的更多信息:

https://www.geeksforgeeks.org/virtual-functions-and-runtime-polymorphism-in-c-set-1-introduction/

关于C++:调用 OBJ、OBJ&、const OBJ& 时实现不同的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48358006/

25 4 0
文章推荐: php -
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com