-1

I have a class with several instances. I also have a global function. I want to access a variable in my class. However, I get an Error that I'm not able to access a nonstatic reference from a static object. Is there a work-around for this?

In one file I would have something like this:

Public class A{
    public: int angle;
}

In another file I would maybe have something like this:

#include "A.h"

void changeAngle()
{
    A.angle = 5;
} 
Fionnuala
  • 90,370
  • 7
  • 114
  • 152
DannyD
  • 2,732
  • 16
  • 51
  • 73

1 Answers1

1

To access a non-static reference means you are trying to access an attribute of an object. To do that, you must have an object:

#include <iostream>
#include <string>

class T
{
    public: 

        std::string s; 

        static const std::string t;  

        T () : s("hey") {}

        const std::string& getS() 
        {
            return s; 
        } 

        static void function()
        {
            // You need an object
            T t; 

            // To access a non-static reference, from anywhere. 
            std::cout << t.getS() << std::endl;

        }
};

const std::string T::t = "ho"; 

int main(int argc, const char *argv[])
{
    // You don't need an object to call a static member funciton.
    T::function(); 

    // Or to access a static attribute.
    std::cout << T::t << std::endl;

    return 0;
}

Output:

hey
ho
tmaric
  • 5,347
  • 4
  • 42
  • 75
  • yes, I thought about making my variable in my first class static. However, it is also used by other functions and can't be static. Is there a way to access the current instance in my global function? Maybe using "this->"? – DannyD Feb 20 '14 at 19:41
  • 1
    Why don't you pass an A object as a non-const ref to the global function? Like `void changeAngle(A& a) { a.x = 10; };`? Or better yet, why not set the angle with a member function `void A::setAngle(int angle) { x = angle; }`? – tmaric Feb 20 '14 at 19:44