首页 > 解决方案 > 类函数调用另一个类函数c ++

问题描述

我有 2 个类 - 具有相同 Print() 功能的商店和所有者。owner::Print() 将打印其数据成员以及所有者拥有的商店。

class store
{
    store(std::string& name)
    {
        name_ = name; //name_ is a private data member
    }

    std::string getName()
    {
        return name_;
    }
    void Print()
    {
        std::cout<<"Store: "<<getName()<<std::endl;
    }
};

class owner
{
    std::string name_;
    std::vector<store> stores;

    public:
    owner(std::string& name)
    {
        name_ = name;
    }

    std::string getName()
    {
        return name_;
    }

    void Print()
    {
        std::cout<<owner.getName()<<"owns: "<<std::endl;
        // I want to call the store::Print()
    }
};

void main()
{
    owner o;
    o.Print();
}

不是真正的代码。只是想要帮助。

标签: c++

解决方案


您必须store在 main 方法中创建该类的一个对象并更改该owner::print()方法以接受 store 的实例。

void store::Print() { 
std::cout<<"Details of store"<<data_members_of_store; 
} 


void owner::Print(store &s) { 
    std::cout<<data_members_of_owner;
    s.Print();
}

此参数将是存储对象,您希望由void owner::Print().


另一种可能且可能更好的解决方案是使用继承,如下所示 -

class owner
{
    owner(std::string& name)
    {
        name_ = name; //name_ is private data member
    }

    std::string getName()
    {
        return name_;
    }

    void Print()
    {
        std::cout<<owner.getName()<<"owns: "<<std::endl;
        // I want to call the store::Print()
    }
};

class store : public owner
{
    store(std::string& name,std::string&owner_name)
    {
        owner(owner_name);
        name_ = name; //name_ is a private data member
    }

    std::string getName()
    {
        return name_;
    }
    void Print()
    { 
        owner::print();
        std::cout<<"Store: "<<getName()<<std::endl;
    }
};

您可以只创建对象store并调用它的 print 方法,该方法也将调用 the owner::print()。如果您想将所有者设为商店的子类,也可以以相反的方式使用此继承。


推荐阅读