首页 > 解决方案 > 在 C++ 中从一个类访问另一个类的变量

问题描述

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

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

更新:当我尝试将 A 对象作为 const-reference 参数传递给 B::print 时,出现错误。在我的示例中,我试图string a从. 现在的问题是我在.void printclass BB.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;
}

#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;
}

溴化氢

#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
}

标签: c++

解决方案


我这样做的方法是将 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 文件?” 或者如果它是“我如何从 B 访问 A 成员变量,而不在 A 中使用静态变量?”

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


推荐阅读