2013-11-03 74 views
1

我對C++比較新,所以我不知道如何實現我的問題。 我將示意性地呈現我的問題而不是實際的代碼,希望這會給出其他用戶也可以使用的一般解決方案。C++:在另一個類的函數中返回對象

我有:

  • 在頭部中阿(及其適當的A.cpp)所定義的A類

  • 在頭部了Bh B類(及其適當的B.cpp)

在這個類B中,我有一個函數,它使用A(objA)的一個對象作爲參數,對它做一些事情並返回這個對象。

我應該如何定義該函數以便類B在其函數中識別「類型」objA? 完成指針,模板,...?

謝謝! Roeland

回答

0

有在那裏變種:

// 1) by value 
    // in B.h 
    #include "A.h" 
    class B { 
    public: 
    A foo(A a); 
    }; 
    // in B.cpp 
    A B::foo(A a) { /* a.do_something(); */ return a; } 

    // 2) by reference 
    // in B.h 
    #include "A.h" 
    class B { 
    public: 
    void foo(A& a); // can modify a 
    void foo(const A& a); // cannot modify a 
    }; 
    // in B.cpp 
    void B::foo(A& a) { // a.change_something(); } 
    void B::foo(const A& a) { // a.get_something(); } 

    // 3) by pointer 
    // in B.h 
    #include "A.h" 
    class B { 
    public: 
    void foo(A* a); // can modify a 
    void foo(const A* a); // cannot modify a 
    }; 
    // in B.cpp 
    void B::foo(A* a) { // a->change_something(); } 
    void B::foo(const A* a) { // a->get_something(); } 
+0

我已經使用了指針版本,它的工作! – Roeland

0

您的headerB.h應該#include "headerA.h"。這就足夠了。

當然,如果你要改變對象的狀態,你應該通過指針來傳遞它,比如void MyBMethod(objA* x);

+0

如果我有一個三等,說什麼C.cpp。 它必須使A(objA)的對象,而不是它使用MyBMethod(objA x)它會改變什麼嗎? – Roeland

+0

然後,您需要將A和B的聲明(頭文件)包含到C.h中(或者,如果您希望在頭文件中使用前向聲明來最小化包含),則需要將聲明(頭文件)包含到C.h中。 – Inspired

相關問題