【发布时间】:2014-04-05 17:59:34
【问题描述】:
我必须创建一个类,在构造函数中,我在创建实例之前验证参数。
为此,我想在类中创建一个静态成员函数,以后可以使用它来验证用户输入(这就是为什么它需要是静态的)。
所以看起来有点像这样:
//.h
...
public:
Constructor(const int thing);
static bool validateThing(int &thing);
...
//.cpp
Class::Constructor (const int &thing):
m_thing = thing;
{
PRECONDITION(validateThing(thing));
// the PRECONDITION macro refers to a homemade function that throws an error
// if the bool in argument is false
}
...
// Later on, in the main file
...
cout << "Enter the thing" << endl;
int thing;
cin >> thing;
cout << "This thing is ";
if (!Class::validateThing(thing))
{
cout << "not ";
}
cout << "valid." << endl;
...
当我尝试构建类时,我收到以下错误消息:
no matching function for call to 'Class::validateThing(int &thing)'
要完成这项工作,我应该了解什么?
【问题讨论】:
-
您将
const int传递给需要非常量intreference 的函数是否有特殊原因?预条件参数 ?并且您可能希望在发布错误内容时指定报告错误的位置(这比大多数人所做的要多,所以至少您可以这样做)。 -
@WhozCraig:对于 const int,我最终做了 rzymek 所说的,所以所有涉及的参数都是 const。至于指定错误报告的位置,我会在以后的问题中记住这一点。感谢您的反馈:)
标签: c++ function class static member