开发者

Enum as a function parameter

开发者 https://www.devze.com 2023-02-01 17:40 出处:网络
is there anything wrong with this code in c++? enum OpenMode{ Read = 0x1, Write = 0x2, Append = 0x4 }; void main(){

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
};
0

精彩评论

暂无评论...
验证码 换一张
取 消