Why was function overloading added to C++?

前端 未结 6 1890
囚心锁ツ
囚心锁ツ 2021-02-03 21:03

I have a C background. I was just wondering why was function overloading added to C++? C doesn\'t have function overloading but C++ does, what was the need for it?

What

6条回答
  •  爱一瞬间的悲伤
    2021-02-03 21:28

    Try to come up with a comfortable way to construct objects if it weren't for function overloading.

    std::string foo = "bar";
    std::vector< std::string > myStringVector;
    myStringVector.push_back( std::string() );
    myStringVector.push_back( std::string( "hello" ) );
    myStringVector.push_back( std::string( foo ) );
    

    A nonsense example, of course, but it illustrates the point.

    Another point would be template programming. You could not come up with generic templates if you had to have a different function name for each parameter type.

提交回复
热议问题