简体   繁体   English

C ++自动转换

[英]C++ auto conversions

For two unrelated classes "class A" and "class B" and a function 对于两个不相关的类“A类”和“B类”和一个函数

B convert(const A&);

Is there a way to tell C++ to automatically, for any function that takes "class B" as argument, to auto convert a "class A". 有没有办法告诉C ++自动,对于任何以“B类”作为参数的函数,自动转换“A类”。

Thanks! 谢谢!

What you would normally do in this case is give B a constructor that takes an A : 在这种情况下你通常会做的是给B一个带A的构造函数:

class B
{
public:
    B(const A&);
};

And do the conversion there. 并在那里进行转换。 The compiler will say "How can I make A a B ? Oh, I see B can be constructed from an A ". 编译器会说:“我怎样才能让A一个B ?哦,我明白了B可以从构建A ”。

Another method is to use a conversion operator: 另一种方法是使用转换运算符:

class A
{
public:
    operator B(void) const; 
}

And the compiler will say "How can I make A a B ? Oh, I see A can be converted to B ". 并且编译器会说“我怎样才能使A成为B ?哦,我看到A可以转换为B ”。

Keep in mind these are very easy to abuse. 请记住,这些很容易被滥用。 Make sure it really makes sense for these two types to implicitly convert to each other. 确保这两种类型隐式转换为彼此确实有意义。

您可以提供强制转换运算符或单参数构造函数。

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

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