首页 > 解决方案 > 如何调用类函数但使用不同的类对象

问题描述

所以我最近刚刚了解了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();
    }

我希望0在使用 B 类对象时打印它。就像在它被调用或编译0后显示一样。"It is A"因为我想看看我使用Bbo.Aprint(). 我想知道如何this工作friend。仍在尝试。

Before it was `Bbo.Aprint()` just edited.

标签: c++

解决方案


我认为您正在尝试通过朋友声明来模仿继承。据我了解,朋友声明允许您从朋友类或函数访问 A 类的私有成员。如果您希望您的 B 类能够调用 A 类函数,我认为您应该使用继承和虚函数。

也许这会对你有所帮助。

https://www.ibm.com/support/knowledgecenter/SS2LWA_12.1.0/com.ibm.xlcpp121.bg.doc/language_ref/cplr042.html


推荐阅读