你如何调用类函数,但使用不同的类对象

How do you call a class function but with a different class object

本文关键字:对象 何调用 调用 类函数      更新时间:2023-10-16

所以我最近刚刚了解了C++friendthis,我正在观看一个针对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()时会发生什么。我想知道thisfriend是如何工作的。仍在试验。

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工作(