将对象指针s的数组从main()
传递到不同类的函数时遇到问题。
我在main()
中创建了一个对象指针listP
的数组,我想用类Manager
中的函数editProduct
修改数组,例如添加新对象或编辑对象。
此外,我想传递整个listP
数组,而不是listP[index]
。如何实现这一点,或者有更好的方法吗?对不起,我对c++很陌生。
#include <iostream>
using namespace std;
class Product
{
protected:
string id, name;
float price;
public:
Product()
{
id = "";
name = "";
price = 0;
}
Product(string _id, string _name, float _price)
{
id = _id;
name = _name;
price = _price;
}
};
class Manager
{
protected:
string id, pass;
public:
Manager(string _id, string _pass)
{
id = _id;
pass = _pass;
}
string getId() const { return id; }
string getPass() const { return pass; }
void editProduct(/*array of listP*/ )
{
//i can edit array of listP here without copying
}
};
int main()
{
int numProduct = 5;
int numManager = 2;
Product* listP[numProduct];
Manager* listM[numManager] = { new Manager("1","alex"), new Manager("2", "Felix") };
bool exist = false;
int index = 0;
for (int i = 0; i < numProduct; i++) { //initialize to default value
listP[i] = new Product();
}
string ID, PASS;
cin >> ID;
cin >> PASS;
for (int i = 0; i < numManager; i++)
{
if (listM[i]->getId() == ID && listM[i]->getPass() == PASS) {
exist = true;
index = i;
}
}
if (exist == true)
listM[index]->editProduct(/*array of listP */);
return 0;
}
由于listP
是指向Product
数组的指针,因此可以使用以下两个选项将其传递给函数。
-
editProduct
可以更改为接受指向大小为N
的数组的指针,其中N
是指向数组的传递指针的大小,在编译时已知:template<std::size_t N> void editProduct(Product* (&listP)[N]) { // Now the listP can be edited, here without copying }
-
或者它必须接受指向对象的指针,这样它才能引用数组
void editProduct(Product** listP) { // find the array size for iterating through the elements }
在以上两种情况下,您都将调用函数作为
listM[index]->editProduct(listP);
也就是说,您的代码有一些问题。
- 首先,数组大小
numProduct
和numManager
必须是编译的时间常数,这样就不会创建非标准的可变长度数组 main
结尾的内存泄漏,因为你没有delete
d,就像你有new
d一样- 还要知道为什么是";使用命名空间std"被认为是不好的做法
- 根据对象在内存中的分配位置,您可以简单地使用
std::array
或std::vector
。这样,您就可以避免内存泄漏和指针语法的所有这些问题
例如,使用std::vector
,您可以简单地执行
#include <vector>
// in Manager class
void editProduct(std::vector<Product>& listP)
{
// listP.size() for size of the array.
// pass by reference and edit the listP!
}
在main()
中
// 5 Product objects, and initialize to default value
std::vector<Product> listP(5);
std::vector<Manager> listM{ {"1","alex"}, {"2", "Felix"} };
// ... other codes
for (const Manager& mgr : listM)
{
if (mgr.getId() == ID && mgr.getPass() == PASS)
{
// ... code
}
}
if (exist == true) {
listM[index]->editProduct(listP);
}
在C++中不能有数组作为参数,只能有指针。由于数组是指针数组,因此可以使用双指针来访问该数组。
void editProduct(Product** listP){
和
listM[index]->editProduct(listP);
当然,这些指针数组都不是必需的。如果只使用正则数组,您可以大大简化代码。
Product listP[numProduct];
Manager listM[numManager] = { Manager("1","alex"), Manager("2", "Felix")};
...
for(int i = 0; i < numManager; i++ ){
if(listM[i].getId() == ID && listM[i].getPass() == PASS) {
exist = true;
index = i;
}
}
if(exist == true){
listM[index].editProduct(listP);
}