从类中的另一个类调用getter

时间:2012-03-26 17:28:17

标签: c++ class getter

我想知道如何从另一个类中的另一个类调用getter函数。例如,我现在所拥有的不起作用

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函数?

4 个答案:

答案 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类首先使用getter,而A类具有委托给b成员变量的getter。

答案 1 :(得分: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
  };

没有编译它,但应该可以正常工作

答案 2 :(得分:0)

您拥有的代码有错误:std::string getfirst(){B中重复两次,这会导致编译错误。

此外,您无需将B声明为A的朋友,因为B并未尝试访问任何A的私人成员。如果你有一个更大的代码,你需要朋友声明,请忽略这一点。

B中使用它之前,您需要定义类A。由于B无法访问A,您只需将其定义放在A之前。

答案 3 :(得分: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
};

我只给骨架。

相关问题