在C ++中将变量从一个类访问到另一个

时间:2018-12-09 16:29:45

标签: c++

我试图从类A访问在类B中声明的变量,而不使用static变量。我将类分为头文件和源文件。

我看到不同的人使用按引用传递(我假设在类定义中声明了“ const&a”),但这对我不起作用。

更新:当我尝试将A对象作为const引用参数传递给B :: print时,出现错误。在我的示例中,我试图从string a中声明的函数void print访问class B。现在的问题是我在B.cpp中遇到错误。

main.cpp

#include <iostream>
#include <string>
#include "A.h"
#include "B.h"

using namespace std;

int main()
{
    A first;
    B second;
    second.print(cout, first);
return 0;
}

A.h

#include <string>

using namespace std;


class A
{
    string a = "abc";
public:
    A();
    void print(ostream& o) const;
    ~A();
};

A.cpp

#include <iostream>
#include <string>
#include "A.h"
#include "B.h"

using namespace std;

A::A()
{
}

A::~A()
{
}

void A::print(ostream& o) const
{
    o << a;
}

ostream& operator<<(ostream& o, A const& a)
{
    a.print(o);
    return o;
}

B.h

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

using namespace std;

class B
{
public:
    B();
    void print(ostream&, A const&) const;
    ~B();
};

B.cpp

#include "B.h"
#include "A.h"
#include <iostream>
#include <string>

using namespace std;

B::B()
{
}
B::~B()
{
}
void B::print(ostream& o, A const& a) const
{
    o << a << endl;
    //^^ error no operator "<<" mathes these operands
}

2 个答案:

答案 0 :(得分:1)

我要做的方法是将A对象作为const-reference参数传递给B :: print。我还要将ostream作为参考参数传递。而且我会利用C ++的流输出运算符(<<)。

赞:

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::ostream;
using std::string;

class A
{
    std::string s = "abc";
public:
    void print(ostream& o) const;
};

void A::print(ostream& o) const
{
    o << s;
}

ostream& operator<<(ostream& o, A const& a)
{
    a.print(o);
    return o;
}

class B
{
public:
    void print(ostream&, A const&) const;
};

void B::print(ostream& o, A const& a) const
{
    o << a << endl;
}

int main()
{
    A first;
    B second;
    second.print(cout, first);
}

更新:鉴于以上评论,我不确定问题是否是“如何将代码拆分为单独的.h和.cpp文件?”或者是“如何在不使用A的静态变量的情况下从B访问A的成员变量?”

更新:我将A的成员变量从a更改为s,以消除与其他a标识符的歧义。

答案 1 :(得分:0)

由于a不是静态成员,因此没有类A的实例就无法访问它。但是,您可以在函数中传递一个:

class B {
    void print(const A &o) {
        cout << o.a << endl;
    }
};

此外,如果a成员是私有成员,则可以将class B声明为朋友,这意味着它可以访问class A的私有成员和受保护成员。

class A {
    friend class B;
private:
    std::string a = "abc";
};
相关问题