简体   繁体   English

C ++子类访问主类变量

[英]C++ subclass accessing main classes variables

I was wondering if a subclass can access variables from the main.cpp file. 我想知道子类是否可以从main.cpp文件中访问变量。 For example: 例如:

Main.ccp Main.ccp

int x = 10;

int main()
{
    return 0;
}

Example Class's cpp 示例类的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 Main.ccp

int x = 10;

int main()
{
    return 0;
}

Example Class's cpp 示例类的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. 您可能想要做的是将x的引用传递给相关的类或函数。

At the very least, it would be a good idea to structure it differently: 至少,以不同的方式构建它是一个好主意:

x.hpp: x.hpp:

extern int x;

x.cpp x.cpp

#include "x.hpp"

int x = 10;

class.cpp: 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. 在class'cpp中添加x的extern声明,然后编译器将在其他cpp文件本身中找到x定义。

A little change to the code: 对代码稍作修改:

Main.cpp Main.cpp的

#include "class.h"

int x = 10;

int main()
{
    return 0;
}

Example Class's cpp 示例类的cpp

#include "class.h"

extern int x;

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

Head file class.h 头文件class.h

class Subclass {
public:
    Subclass ();
};

And for extern keyword, reference this: How do I use extern to share variables between source files? 对于extern关键字,请参考: 如何使用extern在源文件之间共享变量?

C++ is not java. C ++不是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). 解决问题的方法是确保变量是在你使用它的编译单元中定义的,就像Vaughn Cato建议的那样(当我输入它时)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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