1

I create a fraction class,when I call the DtoF(convert double into fraction) function,the compiler said DtoF function is not found(Code:C3861). But the other friend functions,like some overloaded functions (+,-,*,/) works fine.Why? How can I solve the error?

And What's the difference between these overloaded operator functions and my self-defined function?

//fraction.h
class fraction {
private:
    int numerator;
    int denominator;
public:
    //constrctors
    //unary operators
    //overloaded operators
    friend std::ostream& operator<<(std::ostream& os, fraction target);
    ...
    friend fraction DtoF(const double origin);
    ...
}
//fraction.cpp
#include"fraction.h"
//other functions
......
fraction DtoF(const double origin) {
    int num = int(origin * 1000000);
    fraction test(num, 1000000);
    test = test.Reduction();
    return test;
}
std::ostream& operator<<(std::ostream& os, fraction target)
{
//Simpilfied << function    
    return os << target.numerator << "/" << target.denominator;
}

Example

#include<iostream>
#include"fraction.h"
using namespace std;
int main(){
    cout<<DtoF(5.0);
    return 0;
}

Compiler info

~ g++ -c fraction.cpp
~ g++ -c main.cpp
main.cpp: In function 'int main()':
main.cpp:6:10: error: 'DtoF' was not declared in this scope
    6 |  cout << DtoF(5.0);
      |          ^~~~
Victor Hut
  • 35
  • 5
  • Please show the full error message from the compiler and a [mre] – Alan Birtles Jul 14 '22 at 06:31
  • @john sorry,but in my code it's definitely "fraction.h" – Victor Hut Jul 14 '22 at 06:46
  • @VictorHut If you add a prototype for `DtoF` after the class definition it works. But I'm really surprised that is necessary. Maybe someone more expert than me can explain it. – john Jul 14 '22 at 06:51
  • @VictorHut Probably it's got something to do with ADL (argument dependent lookup), the difference with your other operators is that they have parameters of type `fraction`. (but really I'm guessing). – john Jul 14 '22 at 06:55
  • @john So amazing!I add another prototype at the end of the header file,then my program run perfectly!Maybe I should learn more about ADL.Thx! – Victor Hut Jul 14 '22 at 07:00

0 Answers0