【问题标题】:C++ class with static pointer带有静态指针的 C++ 类
【发布时间】:2011-10-25 09:46:58
【问题描述】:

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

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

class foo
{
    public:

    static int *myPtr;

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

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

    return 0;
}

【问题讨论】:

  • 通常,每当您遇到编译器错误时,总是将它们包含在问题中。

标签: c++ class pointers static


【解决方案1】:

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

//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 值。

【讨论】:

  • foo::somfunction也需要返回值
  • 我收到以下错误:无效使用限定名 'foo::myPtr'
  • 非常感谢...我新的必须是简单的东西!
【解决方案2】:
#include <iostream>
using namespace std;

class foo
{
public:

static int *myPtr;

bool somfunction() {
    *myPtr = 1;
    return true;
}
};
//////////////////////////////////////////////////
int* foo::myPtr=new int(5);     //You forgot to initialize a static data member  
//////////////////////////////////////////////////
int main()
{
int flag = 0;
foo::myPtr = &flag;
return 0;
}

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。请阅读此how-to-answer 以提供高质量的答案。
猜你喜欢
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 1970-01-01
  • 1970-01-01
  • 2013-06-14
  • 1970-01-01
  • 2019-04-08
相关资源
最近更新 更多