samedi 31 octobre 2015

Function overloading with different return types

I know we are not allowed to overload functions based on return type only. Suppose I have two functions double convert(string num) and int convert(string num) Consider the following sample code :

double convert(string num){
    stringstream ss;
    double d_num;
    ss<<num;
    ss>>d_num;
    return d_num;
}

int convert(string num){
    int i_num;
    /*.....
   same as previous
   .....
   */
   return i_num;
}

And in the main() :

int main(){
    string st="09122321";
    double d1=convert(st);
    int i1=convert(st);

}

Although I overloaded the function differring only in return type but as I am assigning them to data types based on their return type wasn't I supposed to get the converted string num in double d1 and int i1 ?

Now I get the error similar to:

error: new declaration 'int convert(std::string)'| error: ambiguates old declaration 'double convert(std::string)'|

How will I make the convert() work if I want it to have it different return types by overloading the function ?

Aucun commentaire:

Enregistrer un commentaire