自从我使用 C++ 编码以来已经有一段时间了(18 年以上)。
我在函数中使用默认参数时遇到问题,然后尝试仅使用非默认参数调用该函数。 作为一个例子,这是我的班级声明
//foo.h
#pragma once
struct foo
{
void bar(int, int, int);
void snafu();
}
然后我尝试从
foo::bar(3)
函数中调用 foo::snafu()
。
//foo.cpp
#include "foo.h"
void foo::bar(int x, int y = 1, int z =2)
{
... do stuff
}
void foo:snafu()
{
foo::bar(5) //Error C22660 Function does not take 1 argument
}
我尝试在标题中的函数原型中声明默认值,如下所示
//foo.h
#pragma once
struct foo
{
void bar(int, int valy=1, int valz=2);
void snafu();
}
但这会导致未解决的外部符号链接器错误。
您需要将默认值放在方法的声明中,而不是放在定义中。
foo.h
#pragma once
struct foo
{
void bar(int x, int y = 1, int z = 2);
...
}
foo.cpp
#include "foo.h"
void foo::bar(int x, int y, int z)
{
... do stuff
}
...
此外,您的
foo:snafu()
定义中有 2 个拼写错误。您使用的是 :
而不是 ::
,并且不需要将 bar()
称为 foo::bar()
内部的 snafu()
。
void foo::snafu()
{
bar(5);
}
正如上面所建议的,这是另一个问题的重复。
事实证明,我需要在头文件中定义默认值,然后只在声明中保留没有默认值的参数列表。
谢谢大家的回复!
干杯!