3

I am getting a compiler error when calling a method defined in a derived class. The compiler seems to think that the object I am referring to is of a base class type:

weapon = dynamic_cast<Weapon*>(WeaponBuilder(KNIFE)
.name("Thief's Dagger")
.description("Knife favored by Thieves")
.attack(7)    // error: class Builder has no member called attack 
.cost(10)     // error: class Builder has no member called cost
.build());

Indeed, Builder doesn't contain either attack or cost:

class Builder
{
protected:

    string m_name;
    string m_description;

public:

    Builder();
    virtual ~Builder();
    virtual GameComponent* build() const = 0;

    Builder& name(string);
    Builder& description(string);
};

But the derived class WeaponBuilder does:

enum WeaponType { NONE, KNIFE, SWORD, AXE, WAND };

class WeaponBuilder : public Builder
{
    int m_cost;
    int m_attack;
    int m_magic;

    WeaponType m_type;

public:

    WeaponBuilder();
    WeaponBuilder(WeaponType);
    ~WeaponBuilder();

    GameComponent* build() const;

    // should these be of reference type Builder or WeaponBuilder?
    WeaponBuilder& cost(int); 
    WeaponBuilder& attack(int);
    WeaponBuilder& magic(int);

};

I am not sure why the compiler cannot find the attack or cost method in the WeaponBuilder class, as it is clearly present. I am also not sure why it recognizes the object as an instance of the base class Builder.

4

2 回答 2

6

它找不到它,因为两者都name返回descriptionaBuilder&而不是 a WeaponBuilder&,因此那些其他方法不存在。除了到处强制转换之外,您的代码没有明确的解决方案。

您可以使用CRTP重写整个事情并解决您的问题,但这是一个重大的变化。包括以下内容:

template< typename Derived >
class builder
{
    Derived& name( std::string const& name ){ /*store name*/, return *derived(); }

    Derived* derived(){ return static_cast< Derived* >( this ); }
};

class weapon_builder : builder< weapon_builder >
{
    weapon_builder& attack( int ){ /*store attack*/ return *this; }

    GameComponent* build() const{ return something; }
};

请注意,使用这种方法,所有virtual方法都应该消失,并且您将失去引用普通的能力,builder因为它不再是常见的基类型而是类模板。

于 2012-12-24T16:23:42.403 回答
1

你的意图可能是这样的:

weapon = dynamic_cast<Weapon*>(dynamic_cast<WeaponBuilder &>(WeaponBuilder(KNIFE)
.name("Thief's Dagger")
.description("Knife favored by Thieves"))
.attack(7)    
.cost(10)     
.build());
于 2012-12-24T16:26:07.230 回答