c++ overload

重载(overload) :同一作用域中(函数调用作用域,而不是函数声明作用域),函数名相同,参数表不同的函数。函数指针的重载类型由函数指针参数决定匹配的重载函数

覆盖(override)  :

重写(overwrite):

#include <iostream>
using namespace std;

namespace ns1
{
    void fun(int n)
    {
        cout << "ns1::fun" << endl;
    }
}

namespace ns2
{
    void fun(double n)
    {
        cout << "ns2::fun" << endl;
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    using namespace ns1;
    using namespace ns2;
    fun(3);//ns1::fun
    fun(3.14);//ns2::fun
    
    using ns1::fun;
    fun(3);//ns1::fun
    fun(3.14);//ns1::fun
    
    using ns2::fun;
    fun(3);//ns1::fun
    fun(3.14);//ns2::fun

    void (*pFun)(double) = fun;
    pFun(3);//ns2::fun

    getchar();
    return 0;
}

注意:1)以下构成了重载关系,但是编译器编译不过去,因为重载是依靠的换名机制

extern "C"
{
    int    add(int a, int b)       { return a + b; }
    double add(double a, double b) { return a = b; }
}

               2)注意不要因为使用缺省参数而导致重载歧义

            3)只指定类型不指定名称的函数参数叫做哑元,也可以行程重载版本,对于i++和++i可以用到哑元

#include <iostream>
using namespace std;

void fun(int)
{
    cout << "fun(int)" << endl;
}

void fun(double d)
{
    cout << "fun(double d)" << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    fun(3);//fun(int)
    fun(3.14);//fun(double d)
    getchar();
}




C++中,我们可以使用关键字来隐藏、覆盖和重载成员函数。 1. 隐藏(Hide):当派生类中定义了与基类中同名的成员函数时,基类的成员函数将被隐藏。可以使用作用域解析运算符(::)来访问被隐藏的基类成员函数。 ```cpp class Base { public: void foo() { cout << "Base::foo()" << endl; } }; class Derived : public Base { public: void foo() { cout << "Derived::foo()" << endl; } }; int main() { Derived d; d.foo(); // 输出 Derived::foo() d.Base::foo(); // 输出 Base::foo() return 0; } ``` 2. 覆盖(Override):当派生类中定义了与基类中同名、同参数列表的成员函数时,称为覆盖。在派生类对象上调用该函数时,将执行派生类的实现而不是基类的实现。 ```cpp class Base { public: virtual void foo() { cout << "Base::foo()" << endl; } }; class Derived : public Base { public: void foo() override { // 使用 override 关键字显式声明覆盖 cout << "Derived::foo()" << endl; } }; int main() { Derived d; Base* b = &d; b->foo(); // 输出 Derived::foo() return 0; } ``` 3. 重载(Overload):在同一个作用域内,可以定义多个同名函数但参数列表不同,称为重载。编译器根据函数调用时所传递的参数类型和数量来决定调用哪个函数。 ```cpp class MyClass { public: void foo(int x) { cout << "foo(int): " << x << endl; } void foo(double x) { cout << "foo(double): " << x << endl; } }; int main() { MyClass obj; obj.foo(10); // 输出 foo(int): 10 obj.foo(3.14); // 输出 foo(double): 3.14 return 0; } ``` 希望以上解释能够帮助到你!如果你有更多的问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值