为通过引用传递的参数分配默认值

时间:2012-02-09 05:34:20

标签: c++ pass-by-reference default-value

我想做这样的事情:

int displayAll(Message *m, string &lastIndex, int &NumPrinted = 0 );

它给了我错误,将int转换为int&。

我也试过了:

int temp =0;

int displayAll(Message *m, string &lastIndex, int &NumPrinted = temp );

仍然会出现以下错误:

error: ISO C++ forbids in-class initialization of non-const static member 'temp'

即使static int temp;也会出错。

错误:ISO C ++禁止非const静态成员'temp'

的类内初始化

3 个答案:

答案 0 :(得分:1)

您提到的第一行代码的问题是您尝试将引用传递给临时变量

class Foo {

    int displayAll(Message *m, bool &moreElements, string &lastIndex, int &NumPrinted = 0 );

};

第二位代码抱怨,因为你试图静态初始化一个类成员。

class Foo {

    int temp =0;

    int displayAll(Message *m, bool &moreElements, string &lastIndex, int &NumPrinted = temp );

};

(我将你的代码放在一个类声明中,以明确发生了什么)。

一个不引入静态变量的问题的简单方法是显式函数重载:

class Foo {

    inline int displayAll(Message *m, bool &moreElements, string &lastIndex) {
        int dummy = 0;
        return displayAll(m, moreElements, lastIndex, dummy);
    }
    int displayAll(Message *m, bool &moreElements, string &lastIndex, int &NumPrinted);

};

有一些样板,但它实现了你想要的。 希望这会有所帮助。

编辑:更多说明。问题的核心源于这样一个事实,即函数必须引用它可以修改的某些内存。如果你传递一个临时变量(临时变量,如C ++中术语的含义,而不仅仅是英语术语)(如第一行代码所示),它是非法的C ++,因为你通常会在你之前复制一个临时值将它用作函数的参数:

void bar( int someNum = 0 ); // think of this as creating a temporary rvalue 0
                             // and then copying it into the function for use.

// temporary rvalues arise in expressions like
int v = 5 + 5; // the result of 5 + 5 is stored in a temporary rvalue, and then
               // copied into v (which is an lvalue in this case).

所以我们需要一些“左值”,某个全局变量或某个临时局部变量(在英语语义中),正如我在答案中给出的那样。我准备使用静态变量编写解决方案,但是存在一个很大的缺陷 - 因为静态变量将由类的所有实例共享,它将从0开始,然后每次调用方法时都不同(从那以后)它会被前一个电话编辑)。更糟糕的是,在多线程的情况下,您将从多个处理器读取/写入相同的内存位置,因此该值将是完全垃圾,并且您不应强奸处理器核心的缓存,因为每次写入都会使缓存无效每一个核心。这很难看,请不要这样做。 :P

通过使用我的第一个解决方案,您可以将临时变量设置为非常本地,而不会对其他任何内容产生太大影响。

答案 1 :(得分:0)

除非将temp声明为static,否则不能对非const引用执行此操作:请参阅this stackoverflow post。

答案 2 :(得分:0)

我发现了实现这一目标的有趣方式:

class demo {
public:
        void displayAll(int &x, int y = 0 ) {
            int *p;
            if(y)
                p = (int*)y;
            if(p) *p = 10;

        x = 4;
    }
};


int main() {
    int x=0, y=0;
    demo *obj = new demo();
    obj->displayAll((x);
    //obj->temp(x,(int)&y);
    cout << "\n x= " << x << " y " << y;
    return 0;
}
相关问题