【问题标题】:Why the function doesn't recognize an object created in main()?为什么函数不能识别在 main() 中创建的对象?
【发布时间】:2021-10-22 20:23:31
【问题描述】:

我必须为学校制作一个购物车程序,而这个程序中的活动部分比我以往处理过的要多。我试图弄清楚为什么我的main.cpp 中的函数无法识别我在main() 中创建的对象。它一直在说

 the cart is not declared in the scope. 

我仍然需要完成菜单的构建,但我什至无法让它识别在 main 中创建的对象。

我可以看到该对象正在被正确创建,因为它可以在main() 内进行操作没有问题。此外,我什至有一些占位符命令来让它工作。问题是家庭作业要求菜单在一个函数中。

#include <iostream>
#include <string>
#include "ItemToPurchase.h"
#include "ShoppingCart.h"
using namespace std;

void PrintMenu() 
{
    while (true) 
    {
        string choice;
        cout << "MENU" << endl;
        cout << "a - Add item to cart" << endl;
        cout << "d - Remove item from cart" << endl;
        cout << "c - Change item quantity" << endl;
        cout << "i - Output item's descriptions" << endl;
        cout << "o - Output shopping cart" << endl;
        cout << "q - Quit" << endl;
        cout << endl;
        cout << "Choose an option: " << endl;
        cin >> choice;
        if (choice == "a")      {
            cart.GetDate();
        }
        else if (choice == "d") {
        }
        else if (choice == "c") {
        }
        else if (choice == "i") {
        }
        else if (choice == "o") {
        }
        else if (choice == "q") {
            break;
        }
        else {
            cout << "That is not a valid choice" << endl;
        }
    }
}

int main()
{
    string name;
    string date;
    cout << "Enter customer's name: " << endl;
    cin >> name;
    cout << "Enter today's date: " << endl;
    cin >> date;
    cout << endl;
    cout << "Customer name: " << name << endl;
    cout << "Today's date: " << date << endl;
    ShoppingCart cart(name, date);
    ItemToPurchase apple("apple", 1, 4, "apple");
    cout << cart.GetDate();
    cart.AddItem(apple);
    cout << cart.GetNumItemsInCart();
    PrintMenu();
}
#ifndef SHOPPINGCART_H
#define SHOPPINGCART_H

#include <string>
#include <iostream>
#include <vector>
#include "ItemToPurchase.h"

using namespace std;

class ShoppingCart
{
   private:
       string customerName = "none";
       string currentDate = "January 1, 2016";
       vector<ItemToPurchase> cartItems;
   
   public:
   ShoppingCart(string name, string date);
      string GetCustomerName() const;
      string GetDate();
      void AddItem(ItemToPurchase);
      void RemoveItem(string);
      void ModifyItem();
      int GetNumItemsInCart();
      double GetCostofCart();
      void PrintTotal();
      string PrintDecriptions();         
};
#endif
#include <iostream>
#include <string>
#include <vector>
#include "ShoppingCart.h"
using namespace std;

ShoppingCart::ShoppingCart (string name, string date){
    customerName=name;
    currentDate= date;
}

string ShoppingCart::GetCustomerName() const
{
    return customerName;
}

string ShoppingCart::GetDate() 
{
    return currentDate;
}

void ShoppingCart::AddItem(ItemToPurchase item)
{
    cartItems.push_back(item);
}

void ShoppingCart::RemoveItem(string name)
{
    for (int i = 0; i < cartItems.size(); i++)
    {
        if (cartItems.at(i).GetName() == name)
        {
            cartItems.erase(cartItems.begin() + i);
        }
        else
        {
            cout << "Item not found in cart. Nothing removed." << endl;
        }
    }

}

int ShoppingCart::GetNumItemsInCart(){
    int number;
    number = cartItems.size();
    return number;
}

double ShoppingCart::GetCostofCart()
{
    double sum = 0.0;
    for (int i = 0; i < cartItems.size(); i++)
    {
        sum += cartItems[i].GetQuantity() * cartItems[i].GetPrice();   
    }
    return sum;
}
#include "ItemToPurchase.h"

void ItemToPurchase::SetName(string SetItemName){
    itemName = SetItemName;
}

void ItemToPurchase::SetPrice(int SetItemPrice){
    itemPrice = SetItemPrice;    
}

void ItemToPurchase::SetQuantity(int SetItemQuantity){
    itemQuantity = SetItemQuantity;
}

string ItemToPurchase::GetName() const {
   return itemName;
}

int ItemToPurchase::GetPrice() const {
   return itemPrice;
}

int ItemToPurchase::GetQuantity() const {
    return itemQuantity;
}
#include <string>
#include <iostream>
#ifndef ITEMTOPURCHASE_H
#define ITEMTOPURCHASE_H
using namespace std;

class ItemToPurchase
{
    public: 
    ItemToPurchase(string a, int b, int c, string d)
    {itemName = a;
    itemPrice = b;
    itemQuantity = c;
    itemDescription =d;
    }
        void SetName(string SetItemName);
        void SetPrice(int SetItemPrice); 
        void PrintItemDescription(); 
        void SetQuantity(int SetItemQuantity);
        string GetName() const;
        int GetPrice() const;
        int GetQuantity() const;
        void SetDescription() const;
        string GetDiscription() const;
        void PrintItemCost() const; 
    private:
        string itemName;
        int itemPrice;
        int itemQuantity; 
        string itemDescription;    
};

#endif

【问题讨论】:

  • 这里有很多代码要处理,我不确定你是否会得到任何帮助。我建议从更简单的东西开始,让它发挥作用,然后从那里开始构建。
  • 主要问题实际上来自我认为我使用 Main() 的方式。我只是想我会包括整个事情,以防它以某种方式有所帮助
  • @Eli 如果您在将代码简化为更简单的代码后得到相同的错误(与编译时的第一个错误一样),那么整个事情将无济于事。我要做的第一件事是将您的任务放在一边,将PrintMenu 减少到有问题的行,我认为应该是void PrintMenu(){ cart.GetDate(); },然后将您的其余代码减少到您认为支持它所需的代码在句法上。 (例如,ShoppingCart 唯一需要的成员是 GetDate()。)
  • 此错误的最小化示例示例:Function can't access variable defined in main() function。在另一个问题中,主函数被简化为定义变量并调用另一个函数,而另一个函数被简化为试图访问该变量的一行。所有无关的细节都被删除了。除非您将 std::string 替换为更基本的东西,例如 int,否则无法让它变得更简单。

标签: c++ function class oop scope


【解决方案1】:

[...],但我什至无法识别在main() 中创建的对象。

main()PrintMenu() 是两个不同的函数,作用域不同。一个人无法知道其他人的变量,除非您通过任何方式传递或公开。

在您的情况下,您可以将ShoppingCart 对象(即cart)从main() 传递给PrintMenu 函数,以便在其中知道您的意思是哪个cart

void PrintMenu(ShoppingCart& cart)
//             ^^^^^^^^^^^^^^^^^^^^
{
   // ...
}

并使用ShoppingCart 对象从main() 调用函数。

PrintMenu(cart);

话虽如此;

  • 请不要练习using namespace std;。阅读更多:Why is "using namespace std;" considered bad practice?

  • 如果成员函数不修改成员,则应将该函数标记为const。适用于 ItemToPurchaseShoppingCart 类的所有 getter。

  • 当您在 getter 中返回 non-trivial copyable objects (如 std::string)时,您应该避免复制。这意味着您可能希望对所有返回 std::string 的 getter 进行如下更改:

    const std::string& GetDate() const /* noexcept */
    {
       return currentDate;
    }
    

【讨论】:

  • 做到了!我知道这很简单。非常感谢!
  • 最后一点,您需要注意不要返回对局部变量或临时变量的引用。在这里看起来似乎没问题,因为您正在返回对成员的引用,但请考虑如果其他函数具有 return cart.GetDate(); 会发生什么情况cart 是该函数的本地。
【解决方案2】:

PrintMenu 中的这一行是问题所在:

cart.GetDate();

编译器会在该函数的范围内查找名为 cart 的东西,但它并不存在。解决此问题的方法之一是将 reference 传递给在 main 中创建的 cartPrintMenu 函数:

void PrintMenu(ShoppingCart &cart){

然后像这样调用函数:

PrintMenu(cart);

请注意,因为将来您要修改菜单中的cart,您需要将其作为引用(即使用&amp;)而不是作为副本或常量引用。

【讨论】:

    猜你喜欢
    • 2014-04-22
    • 2018-03-02
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 2016-03-11
    • 2020-12-16
    相关资源
    最近更新 更多