如何使函数变量公开,它们不在类 C++ 中

问题描述

我想知道如何将一个函数的变量公开给其他函数

示例:

void InHere
{
    int one = 1; // I want to be public
}
int main()
{
    InHere(); // This will set int one = 1
    one = 2; // If the variable is public,I should be able to do this
    return 0;
}

有人知道怎么做吗?我在搜索时唯一找到的是类,因为您可以看到类中没有任何内容,而且我不希望它们在一个中。

非常感谢任何帮助!

解决方法

只需将变量设置为全局变量即可。然后你可以从其他功能访问它。

int one;
void InHere()
{
    one = 1; // I want to be public
}
int main()
{
    InHere(); // This will set int one = 1
    one = 2; // If the variable is public,I should be able to do this
    return 0;
}

如果你想在类中使用它,那么试试下面的代码

#include <iostream>
using namespace std;

class My_class
{
    // private members
public: // public section
    // public members,methods or attributes
    int one;
    void InHere();
};

void My_class::InHere()
{
    one = 1; // it is public now
}
int main()
{
    My_class obj;
    obj.InHere(); // This will set one = 1
    cout<<obj.one;
    obj.one = 2; // If the variable is public,I should be able to do this
    cout<<obj.one;
    return 0;
}
,

在函数本地定义的变量通常在该函数之外无法访问,除非该函数明确提供该变量的引用/指针。

一个选项是让函数显式地将指向该变量的引用或指针返回给调用者。如果变量不是 static,则会产生未定义的行为,因为它在函数返回后不存在。

int &InHere()
{
     static int one = 1;
     return one;
}

void some_other_func()
{
     InHere() = 2;
}

如果变量 one 不是 static,这会导致未定义的行为,因为在这种情况下,变量仅在调用 InHere() 时才存在,并在返回时停止存在(所以调用者会收到一个悬空引用 - 对不再存在的东西的引用)。

另一个选项是函数将变量的指针或引用作为参数传递给另一个函数。

 void do_something(int &variable)
 {
      variable = 2;
 }     

 int InHere()
 {
      int one = 1;
      do_something(one);
      std::cout << one << '\n';    // will print 2
 }

缺点是这仅提供对 CALLED BY InHere() 函数的访问。虽然在这种情况下变量不需要是static,但是随着函数返回,变量仍然不复存在(所以如果你想以某种方式组合选项1和选项2,变量需要是{{ 1}})

第三种选择是在文件范围内定义变量,因此它具有静态存储持续时间(即其生命周期与函数无关);

static

可以在任何具有变量声明可见性的函数中访问全局变量。例如,我们可以做

 int one;
 void InHere()
 {
      one = 1;
 }

 void another_function()
 {
      one = 2;
 }

 int main()
 {
     InHere();
        // one has value 1

     some_other_function();
        // one has value 2
 }

并且,在其他源文件中

 extern int one;             // declaration but not definition of one

 int one;                    // definition of one.  This can only appear ONCE into the entire program

 void InHere()
 {
      one = 1;
 }

尽管如此,请小心 - 全局/静态变量有许多缺点,在某种程度上,它们通常被认为是非常糟糕的编程技术。查看 this link(以及从那里链接到的页面)了解一些问题的描述。