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

Chr*_*ian 47 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();
    }
};
Run Code Online (Sandbox Code Playgroud)
    /* 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);

}
Run Code Online (Sandbox Code Playgroud)

而错误来自VC2010

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

Mah*_*esh 136

您必须仅在声明中指定参数的默认值,而不是在定义中指定.

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

 void pBase:: setColor( int _color )
 {
     // ....
 }
Run Code Online (Sandbox Code Playgroud)

成员函数参数的默认值可以是声明或定义,但不能同时进入.引自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
Run Code Online (Sandbox Code Playgroud)

- 末端的例子]

根据标准提供的示例,它实际上应该按照您的方式工作.除非你做了这样,你不应该真正得到错误.我不确定为什么它确实适用于我的解决方案.我想可能是视觉工作室相关的东西.


Mas*_*rHD 12

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

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

#pragma once
Run Code Online (Sandbox Code Playgroud)

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