c++ - 关于多态性的基本问题。基类的 vector ,要派生类。如何?

标签 c++

我想我的设计搞砸了,因为我想保留各种对象类型的 vector 。这些类型都共享一个公共(public)基类。示例:

Class Buick: AmericanCar
{
}

Class Ford: AmericanCar
{
}

然后我做了:

vector<AmericanCar*> cars_i_own;

现在,我有了我的指针 vector ,但我没有我需要的派生类。我考虑过在基类中添加一个 GetType/SetType 函数,然后使用动态转换。虽然这很笨重。我是否为此使用了错误的设计?

最佳答案

好吧,你想用它做什么?获取名称或成本?你会有这样的东西:

class Car
{
public:
    virtual ~Car(void) {}

    virtual std::string location(void) const = 0;
    virtual std::string name(void) const = 0;
    virtual double cost(void) const = 0;
}

class AmericanCar
{
public:
    virtual ~AmericanCar(void) {}

    virtual std::string location(void) const
    {
        return "America";
    }
}

class Buick : public AmericanCar
{
public:
    virtual std::string name(void) const
    {
        return "Buick";
    }

    virtual double cost(void) const
    {
        return /* ... */;
    }
}

class Ford : public AmericanCar
{
public:
    virtual std::string name(void) const
    {
        return "Ford";
    }

    virtual double cost(void) const
    {
        return /* ... */;
    }
}

现在您可以多态地调用这些方法。

不过,这有点奇怪。您不需要像这样存储名称和成本的不同类:

class Car
{
public:
    Car(const std::string& pLocation,
        const std::string& pName,
        double pCost) :
    mLocation(pLocation),
    mName(pName),
    mCost(pCost)
    {
    }

    const std::string& location(void) const
    {
        return mLocation;
    }

    void location(const std::string& pLocation)
    {
        mLocation = pLocation;
    }

    const std::string& name(void) const
    {
        return mName;
    }

    void name(const std::string& pName)
    {
        mName = pName;
    }

    const double cost(void) const
    {
        return mCost;
    }

    void cost(double pCost)
    {
        mCost = pCost;
    }

private:
    std::string mLocation;
    std::string mName;
    double mCost;
}

// make cars
std::vector<Car> cars;
cars.push_back(Car("America", "Buick", /* ... */));

关于c++ - 关于多态性的基本问题。基类的 vector ,要派生类。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1696949/

相关文章:

c++ - foo2.cpp :9: error: expected primary-expression before '(' token

c++ - 使用分配给函数返回值的局部变量或直接使用函数

c++ - FindResource 在加载 png 时出现错误 1813

C++ placement new vs 复制赋值

c++ - 将 MinGW 编译器添加到 QT 5.6.0 Windows

c++ - 将 c 数组分配给 C++ vector

c++ - 使用现有数据结构提升图或将其用作数据结构

C++:无法将指针 vector 分配给另一个指针 vector

c++ - 将两个 RGB 图像组合成一个 6 channel 图像 - openCV

c++ - C 数组 vs 指针 : array is considered as a variable, array+0 被认为是指针?