Reputation: 4607
I have experience in java and I have decided to look at C++. To do this, I thought I'd go through some early (basic) Java examples I have done before, and convert them into C++. Basically I have two classes, 'main' and 'Conversion'
Conversion will convert imperial measurements to kilos.
main gets user input. What I'm trying to do, is pass 2 double values and two strings from main to a method in conversion convert
but im getting the error
missing ';' before ','
for the method call below ( unit1 and unit 2 are double variables)
and then other two are strings
Conversion.convert(unit1, unit2, sUnit1, sUnit2);
this is supposed to send the 4 parameters to this method in conversion.
void convert(double unit1, double unit2, std::string sUnit1, std::string sUnit2)
{
double result1 = calculate(unit1, sUnit1);
double result2 = calculate(unit2, sUnit2);
print(result1+result2);
}
Any ideas why this throws an error? Also say if u need more code, I'm sure this is really obvious but maybe you can see from my code I'm more used to Java.
Upvotes: 0
Views: 439
Reputation: 227370
You cannot call methods on classes like that. Either convert
is a static method, in which case you call it like this:
Conversion::convert(unit1, unit2, sUnit1, sUnit2);
or it is a member function, in which case you need to call it on an instance of Conversion
:
Conversion c;
c.convert(unit1, unit2, sUnit1, sUnit2);
Note that, unlike Java, in C++ you can have "free" functions, i.e. you do not have to place them inside a class. The common practice in these cases is to put functions in namespaces:
namespace Conversions
{
void convert(double d1, double d2, std::string s1, std::string s2) { ... }
}
You can then call it similarly to the static method case:
Conversions::convert(unit1, unit2, sUnit1, sUnit2);
Also note that, unless you are going to make copies of the std::strings
you are passing to the function, it is better to pass by const reference to avoid unnecessary copies:
void convert(double d1, double d2, const std::string& s1, const std::string& s2);
The same applies to the doubles, you can pass them by const reference, but it is hardly worth it given the cost of potentially copying a double.
Finally, main
is the name of a very special function in C++ and C, so you should avoid using it for class names. It is not a keyword, but it could be confusing nonetheless.
Upvotes: 10