search

Home  >  Q&A  >  body text

C++ 函数重载的时候,参数可以用父类类型和子类类型重载吗?

我用C++编程的时候需要对函数进行重载,使函数拥有不同的参数类型,分别是父类类型和子类类型,这样用重载会不会有问题?

黄舟黄舟2807 days ago756

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 15:33:56

    Yes, for example this code.

    #include <iostream>
    class A{
        public:
        int value;
        A(int x):value(x){};
    };
    class B:public A{
        public:
        int base;
        B(int x, int y):A(x),base(y){};
    };
    void print(A a){
        std::cout << a.value << std::endl;
    }
    void print(B b){
        std::cout << b.value << " " << b.base << std::endl;
    }
    int main(){
        A a(1);
        B b(1,2);
        print(a);
        print(b);
        return 0;
    }

    The output is

    1
    1 2

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 15:33:56

    1. Yes, C++ overloading is achieved by renaming the function name when compiling the source file into a target file. The compiler will decide to call you based on the parameters passed in when calling the function. Overloading that specific function is completed during the compilation phase, which is the so-called static polymorphism in C++.

    2. There is also override in C++, which realizes dynamic polymorphism through virtual functions, inheritance, and pointer mechanisms, which is achieved through the virtual table of the runtime class.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 15:33:56

    It doesn’t matter. Such as the answer of @伊仙. ,
    But it won’t work if the parameters are pointers of parent and child types respectively (references are okay).

    reply
    0
  • Cancelreply