C++ C++。。。当所有参数都有默认值时

C++ C++。。。当所有参数都有默认值时,c++,function,arguments,default,C++,Function,Arguments,Default,我想这是一个非常荒谬/基本的问题,但仍然: class m { public: void f(int ***); /***/ } void m::f(int ***a = NULL) { /***/ } 对f的调用(以及对所有参数都具有默认值的任何函数)不接受0个参数。为什么?那么我应该如何格式化声明呢?如果函数定义在头文件中,这就可以了。规则是调用函数的人必须“看到”默认值 所以,我猜函数定义在一个单独的源文件中。假设是这样,只需在函数声明中(在类中)放置默认值: 您还需要从函

我想这是一个非常荒谬/基本的问题,但仍然:

class m
{
public:
   void f(int ***);
  /***/
}
void m::f(int ***a = NULL)
{
  /***/
}

对f的调用(以及对所有参数都具有默认值的任何函数)不接受0个参数。为什么?那么我应该如何格式化声明呢?

如果函数定义在头文件中,这就可以了。规则是调用函数的人必须“看到”默认值

所以,我猜函数定义在一个单独的源文件中。假设是这样,只需在函数声明中(在类中)放置默认值:

您还需要从函数定义中删除默认值,因为您只能在单个位置定义默认值(即使值本身相同)。

这将起作用:

class m
{
public:
   void f(int ***a = NULL);
};

void m::f(int ***a)
{
}

C++中的缺省值是句法糖;编译器实质上是在调用站点为您插入参数。这意味着编译器需要知道默认值是什么,因此它必须由函数声明提供

这也意味着,如果您有继承和虚拟方法,则使用的默认值是来自静态类型(即编译器认为对象是什么类型)的值,而不是来自运行时类型的值。例如:

class Base
{
public:
    virtual ~Base() { }

    virtual std::string foo(std::string s = "b") { return "Base:" + s; }
};

class Derived
: public Base
{
public:
   virtual std::string foo(std::string s = "d") { return "Derived:" + s; }
};

int main(void)
{
   Derived d;
   Base& b = d;
   std::cout << b.foo() << std::endl;
   return 0;
}
类基
{
公众:
虚拟~Base(){}
虚拟std::string foo(std::string s=“b”){return”Base:+s;}
};
类派生
:公共基地
{
公众:
虚拟std::string foo(std::string s=“d”){return”派生:“+s;”
};
内部主(空)
{
导出d;
基数&b=d;

std::cout Oh yeah.相同的文件,但调用在定义之前。很容易猜到原因!尽管我有一种虚构的感觉(当然是基于随机性),认为问题与所有参数都具有默认值的函数有关。干杯!
class Base
{
public:
    virtual ~Base() { }

    virtual std::string foo(std::string s = "b") { return "Base:" + s; }
};

class Derived
: public Base
{
public:
   virtual std::string foo(std::string s = "d") { return "Derived:" + s; }
};

int main(void)
{
   Derived d;
   Base& b = d;
   std::cout << b.foo() << std::endl;
   return 0;
}