SFML community forums

Help => General => Topic started by: guitarmatt99 on September 30, 2013, 08:23:21 pm

Title: Accessing Variables in Functions in Classes!
Post by: guitarmatt99 on September 30, 2013, 08:23:21 pm
Hello, I know there is no SFML in my code but my code was very long so I recreated the problem with a simple program.

What am I doing wrong?

I want to access the String variable that is in a function called MyFunction(); which is in a class called MyClass() but it says String was not declared in this scope.

main.cpp

#include <iostream>
#include <string>
#include "myclass.h"
using namespace std;

int main()
{
    MyClass MyClassOb;
    MyClassOb.MyFunction();

    cout << String.size();
    return 0;
}
 

myclass.cpp

#include "myclass.h"
#include <iostream>
using namespace std;

MyClass::MyClass()
{
    //ctor
}

MyClass::void MyFunction();
{
    string String = "hello";
}
 

myclass.h

#ifndef MYCLASS_H
#define MYCLASS_H

class MyClass
{
    public:
        MyClass();
        void MyFunction();
};

#endif // MYCLASS_H
 
Title: AW: Accessing Variables in Functions in Classes!
Post by: eXpl0it3r on September 30, 2013, 08:36:44 pm
How do you think the String gets out of the class? This is not Java, the "main()" function doesn't belong to the class.
If you want to get the String, you'll havd to return it via a function, e.g
std::string MyClass::getString() {
   return String;
}
 
Title: Re: Accessing Variables in Functions in Classes!
Post by: guitarmatt99 on September 30, 2013, 08:41:05 pm
Thanks! Something so simple, brains not switched on at the moment haha!