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

在我从 main.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

80407 次浏览

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

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


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

成员函数参数的默认值可以放在声明或定义中,但不能同时放在声明或定义中。引自 ISO/IEC14882: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

ー最后一个例子]

根据标准提供的示例,它实际上应该像您所做的那样工作。除非您已经完成了 像这样,否则不应该实际得到错误。我不知道为什么我的解决方案对你有效。可能跟视觉工作室有关。

好吧!它工作(虽然有点奇怪,因为它工作得很好,当我有一个文件中的整个代码)。

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

#pragma once

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

在我的例子中,在多个路径中有相同的头文件。通过删除冗余文件解决了这个错误。