我的程序有一个类似于以下内容的 Car 和 CarManager 类:
#include <list>
class Car
{
public:
void Draw() { Draw(m_opacity); }
void Draw(float opacity)
{
}
private:
float m_opacity;
};
class CarManager
{
public:
//Draw cars using their m_opacity member
void DrawCars()
{
for(auto i = m_cars.begin(); i != m_cars.end(); i++)
i->Draw();
}
//Draw cars using opacity argument
void DrawCars(float opacity)
{
for(auto i = m_cars.begin(); i != m_cars.end(); i++)
i->Draw(opacity);
}
private:
std::list<Car> m_cars;
}
MyApplication::OnRender()
{
CarManager* pCarManager = GetCarManager();
//If this condition is met, I want all cars to be drawn with 0.5 opacity.
if(condition)
pCarManager->DrawCars(0.5f);
//Otherwise, draw cars using their m_opacity value.
else
pCarManager->DrawCars();
}
C++ 不允许将非静态成员用作默认参数,因此我重载了绘图函数。如果未提供参数,将使用类成员调用函数的重载版本。
每辆车都有一个用于渲染的 m_opacity 成员。但是,在某些情况下,我想为所有汽车使用的不透明度指定一个值。在这些情况下,我希望忽略 m_opacity 以支持我提供的值。
在此示例中,CarManager::DrawCars() 中的渲染代码相当小,因此通过对 Car::Draw() 的不同调用重复相同的代码并不是什么大问题。但在我的实际程序中,重复所有相同的代码是不切实际的。
这开始变得困惑了。有没有更好的方法来解决这个问题?
最佳答案
一个简单的方法是使用一个魔法值:
#include <list>
class Car
{
public:
static float noOpacity() { return -1; }
void Draw(float opacity)
{
if (opacity==noOpacity()) {
opacity = m_opacity;
}
// etc.
}
private:
float m_opacity;
};
class CarManager
{
public:
//Draw cars using optional opacity argument
void DrawCars(float opacity = Car::noOpacity(); )
{
for(auto i = m_cars.begin(); i != m_cars.end(); i++)
i->Draw(opacity);
}
private:
std::list<Car> m_cars;
}
关于c++ - 函数重载类设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13337337/