简体   繁体   中英

Pointer to Global Variable as Class Member

I have a class Foo , which I want to be able to write to a global array, Bar .

In Global.h

extern float Bar[256];

In Foo.h

class Foo {
   public:
      Foo(float array[])
      void write(float toWrite);

   private:
      char ptr;
}

In Foo.cpp

Foo::write(float toWrite){
   array[ptr] = toWrite;
   ptr++;
}

In main.cpp :

#include "Global.h"
#include "Foo.h"

Foo foo(Bar);

main(){
  foo.toWrite(100);
}

Is this the correct way to pass a pointer to the global array to the new object? I don't want to create a local copy.

To avoid an XY problem when answering this question. Why do you want to use a global variable? If it's because you want a single instance of Bar across all instances of your class Foo, then you can do this using a static member variable without the need for an ugly global variable. If you want each instance of Foo to map it's Bar array onto a different block of memory then that's a different question.

You also need to initialise the value of your index, here is some example code.

#include <iostream>

class Foo
{
  public:
    Foo();
    void write(float toWrite);

    static float Bar[256];

  private:
    unsigned char index;
};

float Foo::Bar[256] = {0,0,0,0,0};

Foo::Foo(){
  index = 0;
}

void Foo::write(float toWrite){
  Foo::Bar[index++] = toWrite;
}

int main()
{
    Foo foo1, foo2;

    foo1.write(100);
    foo1.write(100);
    foo2.write(200);

    std::cout << Foo::Bar[0] << ", " << Foo::Bar[1] << ", " << Foo::Bar[2] << ", " << Foo::Bar[3] << "\n";
}

Will print out

200, 100, 0, 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM