reference function from another function
I forgot how to reference another function into a function in C++? In python it is declare as a class so that I can use it.
double footInches(double foot)
{
double inches = (1.0/12.00) * foot;
return inches;
}
double inchMeter(double inch)
{
double meter = 39.37 * (footInches(inch));
return meter;
}
I want to reference footInches in inchMeter.
edited
here is the main program
开发者_StackOverflow社区int main()
{
double feet, inch, meter, x = 0;
cout << "Enter distance in feet to convert it to meter: " << endl;
cin >> x;
cout << inchMeter(x);
return 0;
i think the last line is not correct. i want to get the x in footInches first, then go to inchMeter, and then return the answer from inchMeter.
By reference do you mean call?
You are calling the function correctly in your example, but you don't need the surrounding parenthesis.
So simply like this:
double inchMeter(double inch)
{
double meter = 39.3700787 * footInches(inch);
return meter;
}
If your functions exist in different .cpp files, or you need to reference a function that is defined later you can use a forward declaration.
Example:
a.cpp:
double footInches(double foot)
{
double inches = foot * 12.0;
return inches;
}
b.cpp:
double footInches(double foot); //This is a forward declaration
double inchMeter(double inch)
{
double meter = 39.3700787 * footInches(inch);
return meter;
}
The traditional way to "reference" an arbitrary function in C is to use a function pointer. You really don't need it here because you're not going to change the implementation of the toinches function at runtime, but if you need a "reference to a function" you do it like this:
//Declare a function type that does what you want.
typedef double (*inch_converter_t)(double foot)
double footInches(double foot)
{
double inches = (1.0/12.00) * foot;
return inches;
};
//Pass a function pointer to another function for use.
double inchMeter(double inch, inch_converter_t converter)
{
double meter = 39.37 * (converter(inch)); //Making a function call with the pointer.
return meter;
}
int main()
{
inch_converter_t myConverter = footInches;
doube result = inchMeter(42, myConverter); //Call with function pointer.
}
精彩评论