自动铸造 [英] Automatic casts

查看:104
本文介绍了自动铸造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前患有脑屁。我之前做过,但我不记得确切的语法,我不能看看我写的代码,因为我当时在另一家公司工作。我有这样的安排:

I am currently suffering a brain fart. I've done this before but I can't remember the exact syntax and I can't look at the code I wrote because I was working at another company at the time. I have this arrangement:

class P
{
// stuff
};

class PW : public P
{
// more stuff
};

class PR : public P
{
// more stuff
};

class C
{
public:
    P GetP() const { return p; }    
private:
    P p;
};

// ...
    P p = c.GetP( ); // valid
    PW p = c.GetP( ); // invalid
    PR p = c.GetP( ); // invalid
// ...

现在我想让P互换PW和PR(因此PW和PR可以互换)。我可能可以逃避casts,但这个代码更改已经发生了很多次在这个模块单独。我很确定它是一个操作员,但对我的生活我不记得什么。

Now I would like to make P interchangeable with PW and PR (and thus PW and PR can be interchanged). I could probably get away with casts but this code change has occurred quite a few times in this module alone. I am pretty sure it is a operator but for the life of me I can't remember what.

如何使P与PW和PR互换最小量的代码?

更新:要进一步说明。 P代表Project,R和W分别代表Reader和Writer。所有的读者都是加载的代码 - 没有变量,作者有简单的写代码。它需要单独,因为阅读和写作部分有各种管理器类和对话框,这不是项目真正关心的是操作项目文件。

Update: To give a bit more clarification. P stands for Project and the R and W stands for Reader and Writer respectively. All the Reader has is the code for loading - no variables, and the writer has code for simply Writing. It needs to be separate because the Reading and Writing sections has various manager classes and dialogs which is none of Projects real concern which is the manipulation of project files.

更新:我还需要能够调用P和PW的方法。所以如果P有一个方法a()和PW作为方法调用b(),我可以:

Update: I also need to be able to call the methods of P and PW. So if P has a method a() and PW as a method call b() then I could :

PW p = c.GetP();
p.a();
p.b();

基本上是使转换透明。

推荐答案

如果你想要编译这部分:

If you want to get this part to compile:



// ...
    P p = c.GetP( ); // valid
    PW p = c.GetP( ); // invalid
    PR p = c.GetP( ); // invalid
// ...

您需要能够构造/转换P到PW或PR。
您需要这样做:

You need to be able to construct/convert a P into a PW or a PR. You need to do something like this:



class PW : public P
{
    PW(const P &);
// more stuff
};

class PR : public P
{
    PR(const P &);
// more stuff
};

还是你的意思更像:


class P
{
    operator PW() const;
    operator PR() const;
// stuff
};

这篇关于自动铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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