在虚函数中访问派生类成员变量

dek*_*kst 6 c++ polymorphism inheritance templates

class Car {
    class BaseState {
       explicit BaseState(Car* vehicle) : mVehicle(vehicle) {}
       virtual void run() = 0;

       Car* mVehicle;
    }
    class State1 : public BaseState {
       explicit State1(Car* vehicle) : BaseState(vehicle) {}
       virtual void run() {
           // use data of Car
           ...
           doSomething();
       }
       virtual void doSomething() {
       }
    }
    class State2 : public BaseState {
    }
    ...
}

class Convertible: public Car {
    class State1 : public Car::State1 {
       explicit State1(Convertible* vehicle) : Car::State1(vehicle) {}
       virtual void doSomething() {
           static_cast<Convertible*>(mVehicle)->foldTop();
       }
    }
    class State2 : public Car::State2 {
    }
    ...
    void foldTop() {}
}
Run Code Online (Sandbox Code Playgroud)

所有状态都是从BaseState派生的,因此它们具有成员变量mVehicle来访问外部类变量.但是,在每个派生类中,在每个状态的所有函数中,需要static_cast来访问派生类成员变量和函数.

更好的解决方案?

  1. 在派生类的每个状态中,添加另一个指针(例如,Convertible*mConvertible).每个State都有重复的指针(mConvertible和mVehicle)指向同一个对象.看起来不对.
  2. 在基类中使用虚拟Getter而不是mVehicle.基类中会有过多的Getter调用.

================================================== =====================

是.我尝试了如下模板,但它无法编译,因为错误就像

"car.h:在成员函数中'虚拟void Car :: State1 :: run()':car.h:18:12:错误:'mVehicle'未在此范围内声明".

// car.h
#include <iostream>

template <class T>
class Car {
public:
    class BaseState {
    public:
       explicit BaseState(T* vehicle) : mVehicle(vehicle) {}

    protected:
       T* mVehicle;
    };

    class State1 : public BaseState {
    public:
       explicit State1(T* vehicle) : BaseState(vehicle) {}
       virtual void run() {
           mVehicle->x = 1;
           mVehicle->y = 2;
           mVehicle->doSomething1();
           mVehicle->doSomething2();
           processEvent();
       }
       virtual void processEvent() {
           if (mVehicle->val > 2) {
                std::cout << "too large" << std::endl;
           }
       }
    };

    class State2 : public BaseState {
    public:
       explicit State2(T* vehicle) : BaseState(vehicle) {}
       virtual void run() {
           mVehicle->x = 10;
           mVehicle->y = 20;
           processEvent();
       }
       virtual void processEvent() {
           if (mVehicle->val > 20) {
                std::cout << "too large" << std::endl;
           }
       }
    };

    virtual void doSomething1() {
        val += x * y;
    }

    virtual void doSomething2() {
        val += x + y;
    }

protected:
    int x;
    int y;
    int val;

};

// convertible.h
#include "car.h"
#include <iostream>

class Convertible : public Car<Convertible> {
protected:
    class State1 : public Car<Convertible>::State1 {
       explicit State1(Convertible* vehicle) : Car<Convertible>::State1(vehicle) {}
       // want to override functions in base class states
       virtual void processEvent() {
           if (mVehicle->val > 10) {
                std::cout << "too large" << std::endl;
                mVehicle->val = 10;
           }
       }
    };

    // want to override some base class functions
    // and access some special variables
    // want to inherit other functions
    virtual void doSomething2() {
        z = 10;
        val += x + y + z;
    }

protected:
    int z;
};
Run Code Online (Sandbox Code Playgroud)

如果我使用State1(Car* vehicle)而不是State1(T* vehicle),则会有额外的转换错误.我究竟做错了什么?

如果程序能够弄清楚,Convertible::State1::processEvent()应该执行,为什么不能自动转换mVehicleCar*Convertible*?推断时显然mVehicle指向一个Convertible对象Convertible::State1::processEvent().如果有自动演员,我们不需要模板.

n. *_* m. 1

此实现不使用强制转换、重复指针、虚拟 getter 或 CRTP。它具有三个并行的层次结构:

  • 汽车
  • 抽象汽车状态是纯抽象接口
  • 具体汽车状态,其中状态由汽车的实际运行类型参数化。

所以我们有例如

Car                   Car::AbstractState                Car::State<C>
|                     |                                 |
+--- Convertible      +--- Convertible::AbstractState   +--- Convertible::State<C>
|    |                |    |                            |    |
|    +--- Racer       |    +--- Racer::AbstractState    |    +--- Racer::State<C>
+--- Hybrid           +--- Hybrid::AbstractState        +--- Hybrid::State<C>
Run Code Online (Sandbox Code Playgroud)

每个具体状态都派生并实现相应的抽象状态。如果我们有 aCar*指向 a Convertible,并且我们查询它的状态,我们会得到 a Car::AbstractState*,它指向最终类型为 的具体状态对象Convertible::State<Convertible>。然而,汽车层次结构的用户不知道也不关心模板机械。

代码:

#include <iostream>
using namespace std;

struct Trace
{
    Trace(const char* s) : s (s)
    {
        cout << s << " start\n";
    }

    ~Trace()
    {
        cout << s << " end\n";
    }

    const char* s;
};

struct Car {
    struct AbstractState
    {
        virtual void run() = 0;
    };

    template <typename C>
    struct State : virtual AbstractState
    {
        explicit State(C* vehicle) : mVehicle(vehicle) {}
        virtual void run()
        {
            Trace("Car::State::run");
            doSomething();
        };
        virtual void doSomething()
        {
            Trace("Car::State::doSomething");
        }
        C* mVehicle;
    };

    virtual AbstractState* getState() { return new State<Car>(this); }
};


struct Convertible : Car {

    struct AbstractState : virtual Car::AbstractState
    {
        virtual void runBetter() = 0;
    };

    template <typename C>
    struct State : Car::State<C>, virtual AbstractState
    {
        using Car::State<C>::mVehicle;
        explicit State(C* vehicle) : Car::State<C>(vehicle) {}
        void doSomething()
        {
            Trace("Convertible::State::doSomething");
            Car::State<C>::doSomething();
            mVehicle->foldTop();
        }

        void runBetter()
        {
            Trace("Convertible::State::runBetter");
            run();
            doSomethingElse();
        };

        virtual void doSomethingElse()
        {
            Trace("Convertible::State::doSomethingElse");
        }
    };

    void foldTop()
    {
        Trace("Convertible::foldTop");
    }

    Convertible::AbstractState* getState() { return new State<Convertible>(this); }
};

int main ()
{
    Car car;
    Convertible convertible;
    Car& car2(convertible);

    cout << "runing car\n";
    Car::AbstractState* carstate = car.getState();
    carstate->run();

    cout << "runing convertible\n";
    Convertible::AbstractState* convertiblestate = convertible.getState();
    convertiblestate->run();

    cout << "runing car2\n";
    Car::AbstractState* carstate2 = car2.getState();
    carstate2->run();
}
Run Code Online (Sandbox Code Playgroud)