c++ - 在 C++ 中从一个类访问另一个类的变量
问题描述
我正在尝试A
从 class访问在 class 中声明的变量B
,而不使用static
变量。我将类分开在头文件和源文件中。
我见过不同的人使用按引用传递(我假设在类定义中声明了“const &a”),但它对我不起作用。
更新:当我尝试将 A 对象作为 const-reference 参数传递给 B::print 时,出现错误。在我的示例中,我试图string a
从. 现在的问题是我在.void print
class B
B.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
}
解决方案
我这样做的方法是将 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 的成员变量从a
to更改s
为与其他a
标识符消除歧义。
推荐阅读
- java - Spring @DependsOn 使用类而不是 bean 名称
- kubernetes - 如何使用 kubernetes 客户端 Api 部署 ConfigMap
- azure - 从 AzureRM 升级到 Az 模块现在无法使用 Runbook 登录
- typescript - TypeScript:返回与参数相同的类型
- spring-boot - 如何使用 Testcontainers Cassandra 和 Spring Data for Apache Cassandra?
- java - RxJava2 中 onBackpressureBuffer 的行为是什么
- python - 运行耗时功能时如何运行和更新 Tkinter 小部件?
- powerbi - 如何在 power bi 的 DATESBETWEEN 函数中传递月份和年份(例如:Mar-19)?
- python - 如何将此密码学相关代码从 Go 移植到 Python
- django - 嵌套获取或创建功能 - DRF