C ++函数在父返回child [英] C++ function in parent return child

查看:120
本文介绍了C ++函数在父返回child的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说实话,我真的不知道,如何提出这个问题,所以请不要疯了)

To be honest, I don't really know, how to ask this question, so please don't be mad :)

无论如何,我想有我的类中的mutators(setters)返回 this 以允许像jQuery的 a.name(something)。address(somethingelse );
我有一个父类( Entity )和几个子类( Client,Agent等)。大多数事情的变异符都是从 Entity 类(如名称或地址)继承的,但它们返回一个 Entity 对象

Anyway, I want to have the mutators (setters) in my class to return this to allow for jQuery-like a.name("something").address("somethingelse"); I have a parent class (Entity) and several childclasses (Client, Agent etc.). The mutators for most things are inherited from the Entity class (like name or address), but they return an Entity object, so I can't call Client mutators on them.

换句话说:

// name mutator
Entity& Entity::name( const string& name ) {
    // [...] checks
    _name = name;
    return *this;
}

// budgetRange mutator
Client& Client::budgetRange( const long int& range ) {
    // [...] checks
    _budgetRange = range;
    return *this;   
}

那么当我调用它:

Client a; a.name("Dorota Adamczyk").budgetRange(50);

编译器(逻辑上)说,Entity对象没有budgetRange成员(因为name返回一个Entity ,而不是客户端)。

The compiler (logically) says, that the Entity object has no budgetRange member (because name returns an Entity, not a Client).

我的问题是:我怎么能实现这样的?我想到在子类中重载所有的Entity函数,但这不会很好,并会违反继承的想法:)

My question now is: how could I implement something like this? I thought about overloading all the Entity functions in the childclasses but that wouldn't be nice and would be against the idea of inheritance :)

事先感谢你的想法:D

Thank you in advance for your ideas :D

推荐答案

您应该使用 CRTP

template<class Derived>
class Entity
{
    Derived* This() { return static_cast<Derived*>(this); }

public:
    Derived& name(const string& name)
    {
        ...
        return *This();
    }
};

class Client : public Entity<Client>
{
public:
    Client& budgetRange(const long& range)
    {
        ...    
        return *this;   
    }
};

如果要使用虚函数,还可以添加抽象基类, p>

If you want to use virtual functions, you can also add abstract base class, like this:

class AbstractEntity
{
public:
     virtual void foo() = 0;

     virtual ~AbstractEntity();
};

template<class Derived>
class Entity : AbstractEntity
{...};

这篇关于C ++函数在父返回child的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆