c++ - 类函数调用另一个类函数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();
}
这不是真正的代码。只是想要帮助。
解决方案
您必须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()
。如果您想将所有者设为商店的子类,也可以以相反的方式使用此继承。
推荐阅读
- python - 如何安装fiona 1.6?
- google-sheets - 返回排除另一个列表的唯一列表
- shopify - 如何在shopify的产品过滤器和搜索应用程序中手动存储标签?
- maven - 根据maven的官方教程将外部jar安装到本地存储库,但失败
- javascript - 尝试从经典 ASP 调用 javascript 即 JS 文件中的函数
- gradle - 如何仅在发布版本中使用此构建工具(容易出错)?
- php - 我无法弄清楚我遇到的这个 array_map 问题
- php - 如何更正条件 WHERE 和 JOIN sql 表请求?
- marketo - Marketo 通过 REST API 创建潜在客户 - 结果数组的顺序是否与请求中的批处理记录的顺序相同?
- world-of-warcraft - 如何添加自定义治疗药水?