gpt4 book ai didi

C++ : Using a static member function within class

转载 作者:太空宇宙 更新时间:2023-11-04 11:36:34 25 4
gpt4 key购买 nike

我必须创建一个类,在其中的构造函数中,我在创建实例之前验证参数。

为此,我想在类中创建一个静态成员函数,稍后可以使用它来验证用户输入(这就是为什么它需要是静态的)。

所以它看起来有点像这样:

//.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)'

要使这项工作正常进行,我应该了解什么?

最佳答案

进行以下更改:

//.h
public:
Constructor(int thing);
static bool validateThing(int thing);

//.cpp
Class::Constructor(int thing): m_thing(thing)
{
PRECONDITION(validateThing(thing));
//etc.
}

bool Class::validateThing(int thing)
{
//implement here
}

您似乎没有提供 validateThing 的实现。您还应确保声明和定义在参数类型(const/非const、引用等)上达成一致,并正确初始化成员。

构造函数和validateThing 等函数应该采用const& 参数。但对于像 int 这样的简单类型,您也可以按值传递。

关于C++ : Using a static member function within class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22884615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com