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

时间:2016-05-27 19:01:19

标签: c++

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

main.cc:

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

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

file.cc:

#include "header.h"

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

我需要在header.h中放置什么才能使其正常工作?任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:2)

  

如何从另一个.cc文件访问该对象?   我需要在header.h中放置什么才能使其正常工作?

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

在main()中创建的对象持续整个程序。这在嵌入式系统中很常见......我对这方面没有任何问题。

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

main.cc:

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

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

file.cc:

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

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

header.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 ++。

所以,请考虑以下内容(通过引用困境回避传递):

main.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;
}

答案 1 :(得分:0)

如果你想尝试类似......

file.cc:

#include main.cc

编译器将编译main.cc两次 - 这意味着它将在main.cc中看到所有内容的2个定义。这会给你带来一些问题。

更好的设计(并且实际上正确编译!Bonus!)为您的类创建自定义头文件,然后根据需要导入它。

myclasses.h:

Class object;

file.cc:

#include myclasses.h

答案 2 :(得分:0)

这是一个非常糟糕的设计。你不应该在int main中创建一个类对象,并在其他类中使用它。这会降低程序质量并产生更多错误。请阅读有关int main()及其用途的内容。基本上头文件中的所有这些方法都是其他类或程序的API。

因此,最好是在另一个公共类方法中创建一个类的对象,并提供一种通过新类的API访问该对象的方法,如上所述。

要清除它还有一件事 - 不要尝试访问int main()中设置的方法和属性。 int main()用于获取类API提供的方法的输入。