有没有办法通过 main 函数访问受保护的矢量大小而无需将其转换为公共?

Is there a way to access protected vector size via main function without turning it to public?

本文关键字:转换 main 函数 受保护 访问 有没有      更新时间:2023-10-16

我最近一直在开发一个Shape程序(你们中的一些人可能还记得我关于这个的其他问题... ;/(我有一个小问题,我想解决。

在我的 Menu 类中,它包含与菜单相关的所有函数。我有一个unique_ptr向量,其类型为我的基类 Shape,其中包含所有新创建的对象(圆形、矩形等(

protected:
vector<unique_ptr<Shape>> _shapes;

我想创建的函数之一应该根据其索引更改给定形状中变量的值。为此,我计划将矢量打印给用户,然后让他选择要更改的形状的索引。

void Menu::printShapes() const
{
int i = 0;
for (auto p = _shapes.begin(); p != _shapes.end(); p++, i++)
{
cout << i + " ";
(*p)->printDetails();
cout << endl;
}
}

问题在于我的主程序将使用我的菜单功能。因为我不希望用户能够输入我的向量之外的值,所以我必须检查给定的输入是否在 0 和向量大小之间。但是如果不公开向量或从 printShapes(( 函数进行返回语句,我就无法从我的主函数访问此信息,这将使代码变得混乱且不直观,如我所希望的那样。

所以我的问题是:有没有办法在不进行我上面提到的更改的情况下从主函数中找到 Menu 函数中矢量的大小?因为最后我希望能够只做menu.printShapes()然后让用户选择他想要更改的形状的索引

这是我目前的主要功能:


Menu menu;
int input = 0, wait = 0;
while (input != 4)
{
cout << "1: Add New Shape: " << endl;
cout << "2: Modify Existing Shape: " << endl;
cout << "3: Delete All Shapes: " << endl;
cout << "4: Exit: " << endl;
while (input < MIN || input > MAX)
{
cin >> input;
cin.ignore(numeric_limits<streamsize>::max(), 'n');
std::cin >> wait;
}
switch (input)
{
case 1:
{
cout << "1: Circle: " << endl;
cout << "2: Rectangle: " << endl;
cout << "3: Triangle: " << endl;
cout << "4: Arrow: " << endl;
while (input < MIN || input > MAX)
{
cin >> input;
cin.ignore(numeric_limits<streamsize>::max(), 'n');
std::cin >> wait;
}
menu.createShape(input);
}
case 2:
{
/*
I want to be able to access the size of the vector from here
So I could do something like that:
menu.printShapes();
while (input < 0 || input > vectorSize)
{
:Get the index of the shape that the user wants to modify
}
Instant of doing
size = menu.printShapes();
*/
}
}
}

你想太多了。

你只需要添加一个返回向量当前大小的公共函数:

// Declaration in your class
size_t numberOfShapes() const;
// Definition
size_t Menu::numberOfShapes() const
{
return _shapes.size();
}

.然后,当您想知道大小时,调用该函数。

menu.printShapes();
while (input < 0 || input > menu.numberOfShapes())
{
// Get the index of the shape that the user wants to modify
}

简单!

顺便说一句,我想你的意思是>=在那里,而不是>.

您至少有几个选项;具体取决于修改现有形状操作的详细信息。

最简单的方法可能是让 Menu 类型公开一个方法来告诉您它正在管理多少个形状。我同意你不应该公开向量,因为程序不需要知道它是一个特定的向量,但如果"知道菜单正在管理多少个现有形状"是一个要求(似乎是(,那么公开它似乎是合理的。

或者,根据修改操作的返回类型,您可以返回可选或变体。如果你有 7 个形状,我要求你修改第 6 个,那么你可能会告诉我它有效或可能是新的尺寸,但如果我让你修改第 9 个,你可能会告诉我这是一个无效的索引。

区别在于是要求呼叫者被告知并提出有效的问题,还是您希望更强大并回答和处理更广泛的问题。我认为在这种情况下没有太大区别,但我倾向于第二种解决方案,因为这意味着任何潜在的调用者都受到保护,不会超出范围,而不是所有然后必须检查计数然后进行自己的验证。