简体   繁体   English

枚举指针可以指向常量值吗?

[英]Can a Enum pointer point to a constant value?

I am working on some code where I have an 'enum' defined to describe the type of error. 我正在编写某些代码,其中定义了“枚举”来描述错误的类型。 Whenever a certain function is called, it takes an 'enum pointer' as a parameter. 每当调用某个函数时,它都会使用“枚举指针”作为参数。 The function will then set the passed in error variable with a 'constant enum' value. 然后,函数将使用“常量枚举”值设置传入的错误变量。 When I run the program I get a run-time error. 运行程序时,出现运行时错误。 I have provided some of the code to describe my issue: 我提供了一些代码来描述我的问题:

enum error
{
    No_Exist=0, 
    No_Error,
    Unknown,
};

bool process_something(..., error *err)
{
    ....
    ....
    ....
    *err = No_Error;
    return 1;
}

int main()
{
    error *err_val; 
    if(process_something(...,err_val))
    {
    .....
    .....
    }
    .....
    return (0);
}

I want to know whether I can assign the pointer enum variable with the value 'No_Error' or not? 我想知道是否可以为指针枚举变量赋值'No_Error'吗?

When ever you see a function like: 每当您看到类似的功能时:

void foo(int*);

It doesn't mean you need to pass an explicitly declared int* variable. 这并不意味着您需要传递一个显式声明的int*变量。 Following is wrong usage: 以下是错误用法:

int* p;
foo(p);

Following is correct, but not proper: 以下是正确的,但不正确的是:

int* p;
int a;
p=&a;
foo(p); // p points to a

Following is also correct (but again not proper, IMO): 以下内容也是正确的(但再次不合适,IMO):

 int* p;
 p = new int;
 foo(p); // p points to allocated memory

The most correct usage (as per the problem in hand) would be: 最正确的用法(根据当前的问题)将是:

int a;
foo(&a);

Remember that int* (or any T* ) says that pass me an address , and doesn't say pass me a pointer. 请记住, int* (或任何T* )表示向我传递了一个地址 ,而不是向我传递了一个指针。 Another example would be with reference. 另一个例子是参考。 If a function is like: 如果一个函数是这样的:

void bar(int&);

Doesn't mean you must declare a int-reference, and pass it: 并不意味着您必须声明一个int-reference并传递它:

int a;
int &r = a;
bar(r);

But instead pass a itself. 而是通过a本身。 Function needs a reference (L-value). 函数需要参考(L值)。

This: 这个:

int main()
{
    error *err_val; 
    if(process_something(...,err_val))

should be: 应该:

int main()
{
    error err_val; 
    if(process_something(..., &err_val))

You need to pass the address of a valid error to create a pointer to somewhere process_something() can actually write. 您需要传递一个有效error的地址,以创建指向process_something()可以实际写入的位置的指针。 Your code triggers undefined behavior. 您的代码触发未定义的行为。

Now if you must use what you are using you should do it by reference. 现在,如果您必须使用正在使用的内容,则应该参考一下。

For example, 例如,

int readnumber(string userinput, bool* ok);// or your enum instead of a boolean
//
bool okay;
auto val = readstring(someinput,&okay);
if (!okay)
{
    cout << "Something weird but we don't want that to crash our program";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM