简体   繁体   中英

C++ subclass accessing main classes variables

I was wondering if a subclass can access variables from the main.cpp file. For example:

Main.ccp

int x = 10;

int main()
{
    return 0;
}

Example Class's cpp

Subclass::Subclass ()
{
    x = 5;
}

Error:

error: 'x' was not declared in this scope

I am new to coding and I was wondering if this is somehow possible, and if not, how can I do something like this?

This is possible, although generally not a good idea:

Main.ccp

int x = 10;

int main()
{
    return 0;
}

Example Class's cpp

extern int x;

Subclass::Subclass ()
{
    x = 5;
}

Probably what you want to do instead is to pass a reference to x to the relevant classes or functions.

At the very least, it would be a good idea to structure it differently:

x.hpp:

extern int x;

x.cpp

#include "x.hpp"

int x = 10;

class.cpp:

#include "x.hpp"

Subclass::Subclass()
{
    x = 5;
}

Add extern declaration of x in class'cpp, and then the compiler will find the x definition in other cpp file itself.

A little change to the code:

Main.cpp

#include "class.h"

int x = 10;

int main()
{
    return 0;
}

Example Class's cpp

#include "class.h"

extern int x;

Subclass::Subclass ()
{
    x = 5;
}

Head file class.h

class Subclass {
public:
    Subclass ();
};

And for extern keyword, reference this: How do I use extern to share variables between source files?

C++ is not java. You have no main class here, and accessing global variables from a method in a class is not a problem. The problem is accessing a variable that is defined in another compilation unit (another source file).

The way to solve the problem is to make sure the variable is defined in the compilation unit where you use it, either just like Vaughn Cato suggests (while I'm typing this).

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