Quick overview of how I got to this.
- Created the structure
- Created the .cpp file
- Used CMake to create Make file
- Ran Make and received error
I'm trying to compile the following code:
#include <iostream>
using namespace std;
enum UnitType { Meter, Inch };
class Meter {
double value;
public:
Meter(double value) : value(value) {}
double convertTo(UnitType unit) {
if (unit == Inch) {
return value * 39.3700787;
}
};
};
int main (int argc, char *argv[])
{
try
{
Meter meter(1.0);开发者_JAVA百科
}
catch (int e) {
cout << "exception " << e << endl;
}
return 0;
}
but, I'm receiving the following error:
$ make [100%] Building CXX object CMakeFiles/convert-length.dir/convert-length.cpp.o /convert/length/convert-length.cpp: In function ‘int main(int, char**)’: /convert/length/convert-length.cpp:27: error: expected ‘;’ before ‘meter’ make[2]: *** [CMakeFiles/convert-length.dir/convert-length.cpp.o] Error 1 make[1]: *** [CMakeFiles/convert-length.dir/all] Error 2 make: *** [all] Error 2
I'm hoping this is a silly C++ syntax error somewhere that I'm missing, but I've spent a couple hours looking for it with no success. I have little C++ experience, but this code looks syntactically correct. Does anyone see or know what is wrong?
enum UnitType { Meter, Inch };
Here you've defined Meter
as a enumeration value.
class Meter {
...but here (at the same scope) you're trying to re-define it as the name of a class. That's legal, but to make use of it later, you have to use class Meter
, instead of just Meter
:
class Meter meter(1.0);
IMO, even though you can use the same name for both, it's likely to lead to confusion and problems that are much better avoided by simply renaming one or the other (or maybe both).
Couple of things that jumped out at me reading this sample
- The
convertTo
method does not return on all code paths - The
convertTo
method has an;
after the closing}
. - The identifier
Meter
is listed twice: Enumeration value and class name.
As everyone has pointed out: Meter is both an enumeration and a class name.
A little trick that allows you to keep the same name:
class UnitType
{
public:
enum UnitType { Meter, Inch };
};
int main()
{
// Meter enum is now inside the scope of UnitType
UnitType::UnitType type = UnitType::Meter;
Meter meter(1.0);
}
Rename either your enum member "Meter" or class name "Meter"
Change "Meter" in the enum to something else because it conflicts with the class name "Meter".
Secondly, you need to add a return value for the function "convertTo" in the case that "unit != Inch".
Change the enum type into METER and INCH because you even have the class name as Meter.
精彩评论