编译器抱怨我的默认参数?

时间:2011-06-02 04:39:45

标签: c++ class optional-parameters

我遇到了这段代码的麻烦,在我从main.cpp文件中取出这个类并将其拆分为.h和.cpp后,编译器开始抱怨我在void中使用的默认参数。

/* PBASE.H */
    class pBase : public sf::Thread {
private:
    bool Running;

public:
    sf::Mutex Mutex;
    WORD OriginalColor;
    pBase(){
        Launch();
        Running = true;
        OriginalColor = 0x7;
    }
    void progressBar(int , int);
    bool key_pressed();
    void setColor( int );
    void setTitle( LPCWSTR );
    bool test_connection(){
        if(Running == false){
            return 0;
        }
        else{
            return 1;
        }
    return 0;
    }
    void Stop(){
        Running = false;
        if(Running == false) Wait();
    }
};

    /* PBASE.CPP */

    // ... other stuff above

    void pBase::setColor( int _color = -1){
        if(_color == -1){
             SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ),FOREGROUND_INTENSITY | OriginalColor);
             return;
        }
        SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ),FOREGROUND_INTENSITY | _color);

}

错误,取自VC2010

  

错误4错误C2572:'pBase :: setColor':重新定义默认参数:参数1

2 个答案:

答案 0 :(得分:118)

您必须仅在声明中指定参数的默认值,但不能在定义中指定。

 class pBase : public sf::Thread {
     // ....
     void setColor( int _color = -1 );
     // ....
 } ;

 void pBase:: setColor( int _color )
 {
     // ....
 }

成员函数参数的默认值既可以是声明也可以是定义,但不能同时存在。引自ISO / IEC 14882:2003(E)8.3.6

  

6)除了类模板的成员函数之外,出现在类定义之外的成员函数定义中的缺省参数被添加到类定义中的成员函数声明提供的缺省参数集中。类模板的成员函数的默认参数应在类模板中的成员函数的初始声明中指定。 [实施例:

class C { 
    void f(int i = 3);
    void g(int i, int j = 99);
};

void C::f(int i = 3)   // error: default argument already
{ }                    // specified in class scope

void C::g(int i = 88, int j)    // in this translation unit,
{ }                             // C::g can be called with no argument
  

-end example]

根据标准提供的示例,它实际上应该按照您的方式工作。除非您已完成like this,否则您实际上不应该收到错误。我不确定为什么它确实适用于我的解决方案。我猜可能是视觉工作室的相关内容。

答案 1 :(得分:10)

  

好的!它工作(有点奇怪,因为当我将整个代码放在一个文件中时工作正常)。

当我开始将代码移动到多个文件中时,我也遇到了这个问题。真正的问题是我忘了写

#pragma once

位于头文件的顶部,因此它多次重新定义函数(每次从父文件调用头文件时),这导致重新定义默认参数错误

相关问题