【问题标题】:can i access the variable declared in main in any function?我可以在任何函数中访问 main 中声明的变量吗?
【发布时间】:2013-09-28 11:02:37
【问题描述】:

我有两个文件

 books.cpp and books.h

我在我的主要功能中使用这些类。 我在 main.cpp 文件中也有一个函数 func

#include iostream
#include "books.h"
void func(int a, int b);
int main(){
    books book;
    func(5,6);
    return 0;
}

void func(int a, int b){
   //can i use the book object declared in main in this function?
}

我想要函数 main 中声明的 books 类对象 book 我如何访问它? 谁能帮帮我?

【问题讨论】:

    标签: c++ function class variables


    【解决方案1】:

    不直接。您必须将其传递给您的函数或使其成为全局变量。

    void func(int a, int b, books book)
    {
        // use me
    }
    

    【讨论】:

    • 那将是一个不同的对象。
    • 谢谢 =) 会试试这个。全局变量和外部变量之间有什么区别吗?
    • @sara: extern 是访问在另一个 .c(pp) 文件中声明的(全局)变量的关键字
    • @LoztInSpace:添加书籍参考;)
    • @MichałWalenciak 感谢通过引用后的工作 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 2016-02-29
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    相关资源
    最近更新 更多