2012-03-26 19 views
0

別のクラスの別のクラスからゲッター関数を呼び出す方法が不思議でした。たとえば私が今働いているものは動作していませんクラス内の別のクラスからゲッターを呼び出す

class A{ 
public: 
    friend class B; 
std::string getfirst(){ return b.getfirst();} 
private: 
    B b; 
}; 

class B{ 
public: 
    std::string getfirst(){ 
     return first_; 

    } 
private: 
    std::string first_; 

}; 

私はBのgetfirst関数を呼び出すことができるようにこれを修正しますか?

+2

このコードは少しでもコンパイルされません。あなたは 'std :: string getfirst(){std :: string getfirst(){'を持っています。 –

+0

私は「ややコンパイル」の部分が好きでした;-) –

答えて

2

友情は必要ありません。

class B { 
public: 
    std::string get_first() const { return first_; } 
private: 
    std::string first_; 
}; 

class A { 
public: 
    std::string get_first() const { return b.get_first(); } 
private: 
    B b; 
}; 

ここで、クラスBには最初のゲッターがあり、クラスAにはbメンバー変数に代入するゲッターがあります。

+0

私はそれを試しました.Bがgetfirstメンバーを持っていないと言ってコンパイルエラーを返します。 – user798774

+0

タイピングをチェックしてください。私の例では、getfirst()の代わりにget_first()という名前を付けました。 –

0
class B{ 
    public: 
     std::string getfirst(){ 
      return first_; 
     } 
    private: 
     std::string first_; 
    }; 

    class A : public B{ 
     public: 
     //class A has derived the "getfirst" from B 
     private: 
     // add your stuff here 
    }; 

はそれをコンパイルしませんでしたが、

0

にあなたが持っているコードを正常に動作する必要がありますエラーが発生しました:std::string getfirst(){が、これはコンパイルエラーが発生します、Bに2回繰り返します。

また、あなたはBAのプライベートメンバーのいずれかにアクセスしようとしていないとして、Aの友人としてBを宣言する必要はありません。 のコードが大きい場合はこれを無視してにフレンド宣言が必要です。

Aで使用する前に、クラスBを定義する必要があります。 BAにアクセスしませんので、その定義をAの前に置くことができます。

0

これはそれのように補正してもよい

std::string getfirst(){ 
     std::string getfirst(){ 
      return first_;  //cause compilation error 

本当に奇妙です:私は唯一の骨格を与えている

#include <iostream> 
using namespace std; 

class B; // Forward declaration of class B in order for example to compile 
class A 
{ 

public: 

    string getfirst(); 
    friend string :: getfirst(); // declaration of global friend 
}; 

class B 
{ 

public: 

    friend string :: getfirst(); // declaration of global friend 
    friend string A::getfirst(); // declaration of friend from other class 
}; 

+0

それは私のためにコンパイルされませんでした、クラスBはメンバーgetfirstを持っていないと言います – user798774

関連する問題