为什么在类内没有对象的情况下可以调用非静态方法

How come non-static methods can be called without an object inside the class?

本文关键字:情况下 调用 静态方法 对象 为什么      更新时间:2024-09-21

无论在哪里搜索,我都会发现要使用不带对象的方法,唯一的方法就是使其保持静态。然而在下面的代码中,我展示了在没有对象FindIngredientNumPizzas()((*(和(**((的情况下调用非静态方法的两个示例。它会编译,甚至不会发出警告。正如你所看到的,我没有在任何地方使用静态

为什么这是可能的?

class Ingredient {
public:
string Name;
int Price;
string Description;};
class Pizza {
vector<Ingredient> ingredients;
public:
string Name; 
void AddIngredient(const Ingredient& ingredient){ingredients.push_back(ingredient);}
};

class Pizzeria {
map<string, Ingredient> mapNameToIngredient;
map<string, Pizza> mapNameToPizza;

void AddPizza(const string &name, const vector<string> &ingredients)
{
if(mapNameToPizza.find(name) != mapNameToPizza.end())
{
throw runtime_error("Pizza already inserted");
}
else
{
Pizza pizza;
pizza.Name = name;
for(size_t i = 0;  i < ingredients.size(); i++)
{
Ingredient ingredient= FindIngredient(ingredients[i]); //(*)
pizza.AddIngredient(ingredient);
}
mapNameToPizza[name] = pizza;
}
}

void AddIngredient(const string &name, const string &description, const int &price)
{
if(mapNameToIngredient.find(name) != mapNameToIngredient.end())
{
throw runtime_error("Ingredient already inserted");
}
else
{
Ingredient ingredient;
ingredient.Name = name;
ingredient.Price = price;
ingredient.Description = description;                  
mapNameToIngredient[name] = ingredient;
}
}
const Ingredient &FindIngredient(const string &name) const
{
auto it = mapNameToIngredient.find(name);
if(it != mapNameToIngredient.end())
{
return it->second;
}
else
{
throw runtime_error("Ingredient not found");
}
}
};
class Order {
vector<Pizza> pizzas; 
public:
int numOrder;
int NumPizzas() const { return pizzas.size(); }
int ComputeTotal() const;
{
int total = 0;
for(size_t i = 0; i < (size_t)NumPizzas(); i++) //(**) why is it letting me use the method as a static function?
{
total += pizzas[i].ComputePrice();
}
return total;
} 
};

当您从另一个成员函数调用成员函数时,对象是隐含的-它是this->