Hi there. I am in the process of attempting to learn C++ and have what I presume is an elementary problem, but I can't seem to find anything which solves it in either my copy of Stroustrup or online - possibly because I'm unsure what to search on.
As an exercise I have defined a class which will be used to hold angles. The angles will be held internally in Radians, but I want the ability to call a creator with angles in both Radians and Degrees. To this end I've stuck a couple of typedefs as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
typedefdouble Radians;
typedefdouble Degrees;
class Angle
{
staticconstdouble Pi = 3.1415926535897932385;
Radians a;
public:
Angle() {a = 0.0;};
Angle(double d) {a = d;};
Angle(Radians d){a = d;};
Angle(Degrees d) {a = d * Pi/180.0;};
Angle(int d, int m, int s) {a = d + m/60.0 + s/3600.0;};
Radians Get() {return a;};
};
When I try compiling the code (g++ under Linux) I get:
1 2 3 4 5 6 7 8 9 10 11
[tim@tordella scratch]$ g++ -g3 -o angle2 angle2.cpp
angle2.cpp:16: error: ‘Angle::Angle(Radians)’ cannot be overloaded
angle2.cpp:15: error: with ‘Angle::Angle(double)’
angle2.cpp:17: error: ‘Angle::Angle(Degrees)’ cannot be overloaded
angle2.cpp:15: error: with ‘Angle::Angle(double)’
[tim@tordella scratch]$ g++ -g3 -o angle2 angle2.cpp
angle2.cpp:17: error: ‘Angle::Angle(Degrees)’ cannot be overloaded
angle2.cpp:16: error: with ‘Angle::Angle(Radians)’
[tim@tordella scratch]$ g++ -g3 -o angle2 angle2.cpp
angle2.cpp:17: error: ‘Angle::Angle(Degrees)’ cannot be overloaded
angle2.cpp:16: error: with ‘Angle::Angle(Radians)’
I'm sure I'm making an elementary mistake. Can anyone shed any light on what I'm doing wrong.
The problem is that typedefs are not first class types. What I mean by that is that they are simply aliases for the underlying type. That means that you have 3 constructors with what the compiler sees as the same type: double.
You would have to make Radians and Degrees class types to achieve what you are after.