为什么在类内没有对象的情况下可以调用非静态方法
How come non-static methods can be called without an object inside the class?
无论在哪里搜索,我都会发现要使用不带对象的方法,唯一的方法就是使其保持静态。然而在下面的代码中,我展示了在没有对象FindIngredient
和NumPizzas()
((*(和(**((的情况下调用非静态方法的两个示例。它会编译,甚至不会发出警告。正如你所看到的,我没有在任何地方使用静态
为什么这是可能的?
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->
。
相关文章:
- 如果 std::vector::clear() 不是静态的,如何在没有实例的情况下调用它?
- C++ - 如何在不调用其属性的情况下调用类?
- C++ 在不释放内存的情况下调用析构函数
- Python在不引用类名的情况下调用类函数
- 为什么在这种情况下调用非常量右值移动构造函数?
- 是否可以在没有显式专用化的情况下调用可变参数模板函数?
- 使用按引用调用时,不能在没有对象的情况下调用成员函数 const
- 您可以在不调用构造函数的情况下调用攻击器吗?
- 命名空间:不能在没有对象的情况下调用成员函数
- 哪些语言将在没有显式桥接的情况下调用C++
- 如何在不重新索引顶点的情况下调用"boost::remove_vertex"?
- C :在没有对象实例的情况下调用非静态成员函数
- 在不实例化的情况下调用不同派生类的虚拟方法
- C 如何在没有错误的情况下调用void函数
- 在MSVC上的数组初始化期间,destructor在不复制或移动构造方的情况下调用
- 在不指定实例化的情况下调用类模板的静态方法的方法
- 为什么INVOKE总是取消引用数据成员,而不是在可能的情况下调用
- 是否可以在不实例化派生类的情况下调用该类的虚拟函数
- 无法在没有对象的情况下调用成员函数(尽管我相信我确实初始化了它)
- 为什么在没有赋值运算符的情况下调用转换构造函数