简体   繁体   English

C ++类型重载问题

[英]C++ type overloading issue

I have 3 classes in a project, A, B and C. B is derived from A. And B can be constructed from C (it has a constructor B::B(C& c). If a method requires type B, I can use C instance instead. 我在一个项目中有3个类,A,B和C.B来自A.而B可以用C构造(它有一个构造函数B :: B(C&c)。如果一个方法需要B类,我可以请改用C实例。

Although C can be converted to B, I can not pass C directly as a parameter to functions requiring A. 虽然C可以转换为B,但是我不能直接将C作为参数传递给需要A的函数。

void func(A a) {}
C c;
// calling func
func(c); // compile error
func(B(c)); // casting to B first; works.

Is it possible to have func(c) to compile? 是否有可能编译func(c)? Due to some other factors, I cannot add constructor to construct A directly from C: A::A(C&) is not allowed. 由于一些其他因素,我无法添加构造函数直接从C构造A:不允许A :: A(C&)。

This compiles in VS2012: 这在VS2012中编译:

class A { };
class B : public A { };
class C
{
public:
    operator B() { return B(); }   // User defined conversion.
                                   // This is pseudo code just to satisfy the syntax.
};

void func(A a) { }

int _tmain(int argc, _TCHAR* argv[])
{

    C c;
    func(c);
    func(B(c));
}

This is close to your code. 这接近你的代码。 Some adjustments might be needed. 可能需要进行一些调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM