【问题标题】:The compiler is complaining about my default parameters?编译器抱怨我的默认参数?
【发布时间】:2011-09-06 19:35:03
【问题描述】:

我在处理这段代码时遇到了问题,在我从 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

【问题讨论】:

    标签: c++ class optional-parameters


    【解决方案1】:

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

     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
    

    ——结束示例]

    根据提供的标准示例,它实际上应该按照您的方式工作。除非你已经完成了like this,否则你实际上不应该得到错误。我不确定为什么它在我的解决方案中实际上适用于您的情况。我猜可能与视觉工作室有关。

    【讨论】:

    • 好的!它工作(虽然有点奇怪,因为当我将整个代码放在一个文件中时它工作正常)。
    • 啊!每次都得到我!
    【解决方案2】:

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

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

    #pragma once
    

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

    【讨论】:

    • 谢谢你,我开始认为我会因为这个错误而失去理智。
    【解决方案3】:

    就我而言,我在多个路径中有相同的头文件。错误通过删除冗余文件解决。

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 2012-06-29
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多