c++ - 如何使用在其他文件中定义的 C++ 对象?

标签 c++

我一直有这个问题。如果我在 main.cc 中定义一个对象,我如何从另一个 .cc 文件访问该对象?

主.cc:

#include "Class.h"
#include "header.h"

int main()
{  
    Class object;
    return 0;
}

文件.cc:

#include "header.h"

void function()
{
    object.method(parameter);
}

我必须在 header.h 中放入什么才能让它工作?任何帮助将不胜感激。

最佳答案

how do I access that object from another .cc file? What would I have to put in header.h to get this working?

简单的答案是“通过引用传递对象”。

在 main() 中创建的对象持续整个程序。这在嵌入式系统中很典型……我在这方面没有问题。

但是,我会把持久对象放在动态内存中(因为堆栈更有限)。

主.cc:

#include "Class.h"
#include "header.h"

int main()
{  
    Class* object = new Class;
    function(*object);  // <--- pass the object by reference
    return 0;
}

文件.cc:

#include "Class.h"
#include "header.h"

void function(Class& object)  // <-- how to specify reference
{
    object.method(parameter);  // <-- you did not identify parameter
}

标题.h

class Class;   // <--- poor name choice

void function (Class& object);  // <--- another poor name choice

// note that the compiler needs to know only that Class is a 
// user defined type -- the compiler knows how big a reference
// or ptr to the class is, so you need not provide more Class info
// for this file

当然还是要写Class.h,定义Class


更新 - 您已将这篇文章标记为 C++。

因此,请考虑以下内容(避免了引用传递的困境):

主.cc:

#include "Class.h"
#include "header.h"

int main()
{  
    Class* object = new Class;
    // 
    // I recommend you do not pass instance to function.
    //
    // Instead, the C++ way is to invoke an instance method:

    object->function(); 

    // and, if you've been paying attention, you know that the method 
    //      Class::function() 
    // has access to the 'this' pointer of the class
    // and thus the 'passing' of this instance information
    //     is already coded!

    // some of your peers would say you must:
    delete object;
    // others would say this is already accomplished by the task exit.
    return 0;
}

关于c++ - 如何使用在其他文件中定义的 C++ 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37490613/

相关文章:

c++ - 了解 cout.operator<<() 的行为

c++ - 如何改变MFC PropertySheet的字体

c++ - 如何终止 cin>> 输入特定的单词/字母/数字/等

c++ - 传递所有元素为零的数组 (C++)

c++ - QT通过C++添加Map QML Items

c++ - 如何编译 Freetype (2) 和 Harfbuzz (with visual studio) 让它们协同工作?

c++ - C++ 中的 3d 卷积

c++ - std::chrono::duration::max() 不适用于线程支持库

python - 停止 VTK 定时器回调

c++ - 为什么 cout.setf(ios::fixed) 将我的 float 更改为十六进制?