你如何调用类函数,但使用不同的类对象
How do you call a class function but with a different class object
所以我最近刚刚了解了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();
}
我希望它在我使用 B 类对象时打印0
。就像在"It is A"
后显示0
何时调用或编译时一样。因为我想看看当我使用Bbo.Aprint()
时会发生什么。我想知道this
和friend
是如何工作的。仍在试验。
Before it was `Bbo.Aprint()` just edited.
我认为您正在尝试通过朋友声明来模仿继承。据我了解,好友声明允许您从友元类或功能访问 A 类的私人成员。如果你想让你的类 B 能够调用类 A 函数,我认为你应该使用继承和虚函数。
也许这会对你有所帮助。
https://www.ibm.com/support/knowledgecenter/SS2LWA_12.1.0/com.ibm.xlcpp121.bg.doc/language_ref/cplr042.html
不能使用一个类的实例调用另一个类的成员函数(除非这些类通过继承关联(:
Abo.Aprint(); // OK
Bbo.Aprint(); // Not OK
有一种方法可以做到这一点。为此,您必须将A::Aprint
的签名更改为void Aprint(const B&);
#include <iostream>
class B; // forward declaration
class A
{
public:
void Aprint(const B&);
private:
int Number = 1;
};
class B
{
public:
void Bprint()
{
std::cout << "It is B " << std::endl;
}
private:
int Number = 0;
friend void A::Aprint(const B&);
};
void A::Aprint(const B& b) {
std::cout << "It is A " << b.Number << std::endl;
}
int main()
{
A Abo;
B Bbo;
Abo.Aprint(Bbo);
}
在这个例子中,因为A::Aprint()
是B的朋友,所以Aprint()
甚至可以访问Bbo的私人成员(即使它是私有的,也可以看到b.Number
工作(
相关文章:
- 使用 gmock c++ 在真实对象上调用方法
- 根据对象类调用不同的方法
- 如何获取列表的每个对象并调用getName方法来打印其名称
- 在之后仍需要使用源对象时调用父移动分配运算符
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 为什么指针对象没有调用默认构造函数
- 实例化对象并调用方法,使用单行语法在 C# 或 C++ 中返回值?
- 通过 id 访问 QML 插槽中的嵌套对象(从 c++ 调用)
- 对std::函数对象的调用不匹配,该对象是指向成员函数的指针
- 在创建对象向量时,不为每个对象唯一调用默认对象构造函数
- 编译器是否在由 new 初始化的对象上调用隐式析构函数
- C++:在共享对象中调用抽象基类构造函数/未定义的符号
- C++ abort() 在函数内的抽象类对象指针调用上
- 我的一些 D3D11 对象在调用某些设备上下文函数时将自身作为 ComPtrs 为空
- 静态对象如何调用私有构造函数
- 应该在成员对象上调用析构函数
- 在 const 对象上调用非 const 函数
- 运算符 () 括号是否会在函数调用中创建的对象上调用
- 线程在销毁包含该线程的对象时调用 thread.detach()
- 析构函数是否可以在 const 对象上调用非 const 函数