Enum as a function parameter
is there anything wrong with this code in c++?
enum OpenMode{
Read = 0x1,
Write = 0x2,
Append = 0x4
};
void main(){
open_file("./something", OpenMode::Write); //!!!!!!!!!
}
void open_file(string name, OpenMode om){
.
.
.
}
All i need to do is to pass an enum to function without creating an instance of it.
Ok开发者_Python百科, Have you ever noticed the way ios works? For example:
somefile.open(file_name, ios::in | ios::out)
I need a way to do something like this: "something::something"!
Yes, there's something wrong. The names created by a enum
go into the scope that contains the enum
, they are not qualified by the enum
's name.
In C++0x, there's a new "enum class" syntax that nests the names within the enum.
A workaround in C++03 is to use a struct or namespace, i.e.:
namespace OpenMode
{
enum OpenMode
{
Read = 0x1,
Write = 0x2,
Append = 0x4
};
}
// blah blah OpenMode::Write
Unfortunately it also changes the type name to OpenMode::OpenMode
.
main's signature should be
int main()
or
int main(int, char *[])
missing comma , in your enum
enum OpenMode
{
Read = 0x1, // use commas to delimit enum constants, not semicolons
Write = 0x2,
Append = 0x4
};
精彩评论