请问如何创建铸造操作员? [英] Please how do I create a casting operator?

查看:60
本文介绍了请问如何创建铸造操作员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于班级



Given the class

class Subclass1;
class subclass2;

class MyClass
{
 Subclass1 m_subclass1;
 Subclass2 m_subclass2;
}



请写一个运算符的格式是什么样的演员:


Please what is the format for writing an operator such that the cast:

MyClasss obj;
Subclass1 *obj1 = (Subclass1 *)obj;
Subclass2 *obj2 = (Subclass2 *)obj;





将成功,返回指向子对象的指针。 />
我需要的只是原型的格式,我可以从那里继续。如果我愿意,我可以让操作符返回副本或引用而不是指针。



Will succeed, returning the pointers to the sub objects.
All I need is the format of the prototype, I can continue from there.If I wish I can make the operator return a copy or reference rather than a pointer if I so desire.

推荐答案

在不破坏事物的情况下,不能将不同的类型相互转换。请参阅 http://msdn.microsoft.com/en-us/library/ cscsdfbt(v = vs.71).aspx [ ^ ]。
You cannot cast different types to one another without breaking things. See http://msdn.microsoft.com/en-us/library/cscsdfbt(v=vs.71).aspx[^].


class A
{
};

class B
{
};

class C
{
    A a;
    B b;
public:
    operator A* (){return &a;}
    operator B* (){return &b;}
};

int main()
{
    C c;
    A * pa = (A*) c;
    B * pb = (B*) c;
}


如对解决方案2的回复中所述,我怀疑是否有必要将此功能用作转换操作。为什么?因为你并没有真正将对象转换为其他东西。您只需要访问其中一个内部,这通过普通的旧成员函数自然实现。



我将如何做:



As mentioned in a reply to Solution 2, I doubt that it's necessary to phrase this feature as a casting operation. Why? Because you're not really casting the object to something else. You simply need access to one of its internals, which is naturally achieved through plain old member functions.

How I would do it:

class A {};
class B {};

class C
{
    A a_obj;
    B b_obj;

public:    
    A const &getA() const;
    A &getA();

    B const &getB() const;
    B &getB();
};

int main()
{
    C c1;
    C const c2;

    A &a1 = c1.getA();
    A &a2 = c2.getA(); // Compiler error, assigning const& to non-const
    A const &a3 =  c2.getA(); // OK!
    // same for B
}





请注意通过让 const 成员返回 const 引用来确保对象的完整性。



Notice that the integrity of the object is ensured by having the const members return const references.


这篇关于请问如何创建铸造操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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