C++ 函数重载的时候,参数可以用父类类型和子类类型重载吗?
黄舟
黄舟 2017-04-17 15:31:56
0
3
731

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

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
Ty80

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
洪涛
  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.

伊谢尔伦

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).

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!