Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Accessing Variables in Functions in Classes!  (Read 1339 times)

0 Members and 1 Guest are viewing this topic.

guitarmatt99

  • Newbie
  • *
  • Posts: 19
    • View Profile
Accessing Variables in Functions in Classes!
« 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
 

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11030
    • View Profile
    • development blog
    • Email
AW: Accessing Variables in Functions in Classes!
« Reply #1 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;
}
 
« Last Edit: September 30, 2013, 08:52:40 pm by eXpl0it3r »
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

guitarmatt99

  • Newbie
  • *
  • Posts: 19
    • View Profile
Re: Accessing Variables in Functions in Classes!
« Reply #2 on: September 30, 2013, 08:41:05 pm »
Thanks! Something so simple, brains not switched on at the moment haha!

 

anything