2012-06-12 39 views
2

在C++中,我有:代表在C + +(或這樣的事情)

//Base1.h 
#ifndef BASE1_H 
#define BASE1_H 
#include <iostream> 
#include <string> 
#include "Base2.h" 

using namespace std; 

class Base1{ 
    private: 
     string name; 
    public: 
     Base1(string _name); 
     void printSomething(); 
     string getName(); 
}; 
#endif 

Base1.cpp我實現構造Base1(string _name)string getName()爲正常,並且printSomething()

void Base1::printSomething(){ 
    Base2 b2; 
    // how to pass a parameter in the following code? 
    b2.printBase1(); 
} 

// This is Base2.h 
#ifndef BASE2_H 
#define BASE2_H 

#include <iostream> 
#include <string> 
#include "Base1.h" 

using namespace std; 

class Base2{ 
    public: 
     Base2(); 
     void printBase1(Base1 b); 
}; 
#endif 

而且Base2()構造我像往常一樣執行,這是我的printBase1(Base1 b)

void Base2::printBase1(Base1 b){ 
    cout << b.getName(); 
} 

所以,最後,我想在Base1類中使用printSomething(),但我不知道如何將參數傳遞給b2.printBase1()printSomething(),如上所示在我的代碼中。在C++中有沒有像b2.printBase1(this)?如果不是,你能給我一個建議嗎?

回答

3

由於this在C++中的指針,你需要取消對它的引用:

b2.printBase1(*this); 

請注意,您有圓形包括,你應該從Base1.h刪除#include "Base2.h"。還要查看傳入參數(const)引用,特別是對於非POD類型,否則您可能無法獲得預期的行爲。

例如,你的簽名是

void printBase1(Base1 b); 

當你調用它,你在函數創建參數的副本,因此在副本上運行。只有當你確定你需要副本按值

void printBase1(Base1& b); 

void printBase1(const Base1& b); //if you don't change b 

通行證:你應該更改爲。

+0

如果我刪除'Base2.h',如何在printSomething()中創建'Base2 b2''?我得到了一個錯誤:(! –

+1

@Kingfisher你把它包含在cpp文件中,而不是頭文件 –

+0

謝謝,但我不會改變'void printBase1(Base1 b)',我仍然得到一個正確的結果! ? –

相關問題