c++ - 函数重载类设计

标签 c++ overloading default-arguments

我的程序有一个类似于以下内容的 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/

相关文章:

c++ - 如何在模板类的成员中使用重载的原始 exp

c++ - 具有默认参数的成员初始化列表

c++ - 在 lambda 定义中无效使用非静态数据成员

javascript - 删除特定参数

c++ - 从派生类构造函数初始化 protected 数据成员

c++ - 是否有 QFileinfo::Owner() 的 Windows 等价物?

c++ - 如何在 XP 样式按钮上显示位图/图标

c++ - 按行解析和排序 csv 文件

javascript - 将 @grant 添加到 GM 脚本会破坏 XMLHttpRequest.prototype.open 的过载吗?

java - 可选数组支持的重载 - Java