Gus*_*o99 8 c++ inheritance overloading
我是C++的初学者,我想更改将在此代码中调用的函数版本:
#include <iostream>
class C1 {};
class C2 : public C1 {};
void func(C1 var) {
    std::cout << "Func 1" << std::endl;
}
void func(C2 var) {
    std::cout << "Func 2" << std::endl;
}
int main() {
    C1 *teste1 = new C1;
    C1 *teste2 = new C2;
    func(*teste1);                 // Want "Func 1"
    func(*teste2);                 // Want "Func 2"
    return 0;
}
正如在注释中可以看到的那样,我想要的是当我取消引用指向C2类的指针时调用带有C2参数的func.
编辑:为了澄清我真正想要实现的目标,以下代码更接近我想要的:
#include <iostream>
#include <list>
class C1 {};
class C2 : public C1 {};
void func(C1 var) {
    std::cout << "Func 1" << std::endl;
}
void func(C2 var) {
    std::cout << "Func 2" << std::endl;
}
int main() {
    std::list<C1*> teste;
    teste.push_back(new C1);
    teste.push_back(new C2);
    // Want to print:
    // Func 1
    // Func 2
    for(auto i: teste) {
        func(*i);
    }
    return 0;
}
C2如果你知道你正在处理一个 C2 对象,你可以先转换为指针:
func(*teste1);                   // Want "Func 1"
func(*static_cast<C2*>(teste2)); // Want "Func 2"
或者,您可以C2通过在 中使用虚函数来实现多态C1:
class C1 {
public:
    virtual ~C1() {}
};
然后你可以做一个dynamic_cast:
func(*dynamic_cast<C2*>(teste2)); // Want "Func 2"
请注意,如果您不确定自己拥有哪种类型的对象,则dynamic_cast失败时将返回空指针,因此您可以执行以下操作:
if(dynamic_cast<C2*>(teste2)) {
    func(*dynamic_cast<C2*>(teste2)); //If it's a C2, call the C2 overload
} else {
    func(*teste2); //If it's a C1, call the C1 overload
}
或者更好的是,如果可以避免的话,根本不要使用指针!