gpt4 book ai didi

带有静态指针的 C++ 类

转载 作者:可可西里 更新时间:2023-11-01 17:10:48 27 4
gpt4 key购买 nike

我还不是很了解指针和引用,但我有一个包含静态方法和变量的类,它们将从主类和其他类中引用。我在 main() 中定义了一个变量,我想将其传递给此类中具有静态函数的变量。我希望这些函数更改在 main() 范围内看到的变量的值。

这是我正在尝试做的一个例子,但是我遇到了编译器错误...

class foo
{
public:

static int *myPtr;

bool somfunction() {
*myPtr = 1;
return true;
}
};

int main()
{
int flag = 0;
foo::myPtr = &flag;

return 0;
}

最佳答案

提供类外静态变量的定义为:

//foo.h
class foo
{
public:

static int *myPtr; //its just a declaration, not a definition!

bool somfunction() {
*myPtr = 1;
//where is return statement?
}
}; //<------------- you also forgot the semicolon


/////////////////////////////////////////////////////////////////
//foo.cpp
#include "foo.h" //must include this!

int *foo::myPtr; //its a definition

除此之外,您还忘记了上面评论中指出的分号,somefunction 需要返回一个 bool 值。

关于带有静态指针的 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7033649/

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