c++ - 如何调用类函数但使用不同的类对象
问题描述
所以我最近刚刚了解了C++ 的friend
和this
,我正在看一个针对 C++ 和编程初学者的教程。我对this
语法或任何东西很感兴趣,他说它是一个指针并存储对象的地址,所以我尝试了它。
顺便说一句,是否可以使用来自不同类函数的不同类对象?如果是这样,怎么做?
无论如何这里是代码
||
\/
#include <iostream>
class A
{
public:
void Aprint()
{
std::cout << "It is A " << this->Number << std::endl;
}
private:
int Number = 1;
};
class B
{
public:
void Bprint()
{
std::cout << "It is B " << std::endl;
}
private:
int Number = 0;
friend void A::Aprint();
};
int main()
{
A Abo;
B Bbo;
Abo.Aprint();
}
我希望0
在使用 B 类对象时打印它。就像在它被调用或编译0
后显示一样。"It is A"
因为我想看看我使用Bbo.Aprint()
. 我想知道如何this
工作friend
。仍在尝试。
Before it was `Bbo.Aprint()` just edited.
解决方案
我认为您正在尝试通过朋友声明来模仿继承。据我了解,朋友声明允许您从朋友类或函数访问 A 类的私有成员。如果您希望您的 B 类能够调用 A 类函数,我认为您应该使用继承和虚函数。
也许这会对你有所帮助。
推荐阅读
- java - 将文件从 GWT 上传到另一个域,响应始终为空
- vue.js - Nuxt fetch() 多次调用
- json - Laravel - Json 编码工作正常,但无论如何都会返回格式错误的 UTF-8 错误
- python - 当 Python 64 位内存不足时究竟会发生什么?
- sharepoint - PnPJS 更新项目 - 列表数据验证失败
- sql - 不能按功能使用分组
- c# - 如何在不重复代码的情况下在表单的所有 Load 事件中调用方法?
- reactjs - 如何更改输入元素中的值?(反应)
- apache-spark - Spark 如何加速 JanusGraph 的批量加载?
- r - 带 dplyr 的加权条件和