我有一个称为“Integer”的习俗类别,我要告诉汇编者,如何将某些类型自动转换为“Integer”,以便我能够避免重复打上同样的字,
someCall(Integer(1), Integer(2));
届时将开始
someCall(1,2);
我ve笑,但我可以发现的是,做的是眼镜,给我带来反面的愤怒。
我有一个称为“Integer”的习俗类别,我要告诉汇编者,如何将某些类型自动转换为“Integer”,以便我能够避免重复打上同样的字,
someCall(Integer(1), Integer(2));
届时将开始
someCall(1,2);
我ve笑,但我可以发现的是,做的是眼镜,给我带来反面的愤怒。
书写带<代码>int的构造:
class Integer
{
public:
Integer(int);
};
如果类别<代码>Integer有这种构造者,则您可以这样做:
void f(Integer);
f(Integer(1)); //okay
f(1); //this is also okay!
解释是,在你撰写<代码>f(1)时,采用<代码>Integer<>/code>的构造者,自动被称作“密码>int,在传单上设定一个临时性,然后临时转至该功能!
现在,你想要做的是相反的事情,即通过一个类型的标的<条码>/条码>,以履行以下职能:<条码>。
void g(int); //NOTE: this takes int!
Integer intObj(1);
g(intObj); //passing an object of type Integer?
为了使上述代码发挥作用,你需要确定这一类别中的用户定义转换功能如下:
class Integer
{
int value;
public:
Integer(int);
operator int() { return value; } //conversion function!
};
因此,当您通过<代码>Integer的功能,即int
时,转换功能即被援引,而标语则改写为int
,然后作为理由转至该功能。 也可以这样做:
int i = intObj; //implicitly converts into int
//thanks to the conversion function!
你们可以就你想要暗中转换的那类建筑群进行定义。 不要将其编成<条码>。
Nawaz has given the correct answer. I just want to point out someting. If the conversion operator is not const, you can t convert const objects
const Integer n(5);
int i = n; // error because non-const conversion operator cannot be called
更好地申报您的转换经营人
operator int() const {return value;}
I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...
I have been searching for sample code creating iterator for my own container, but I haven t really found a good example. I know this been asked before (Creating my own Iterators) but didn t see any ...
Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...
I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?
Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...
Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...
I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...
Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?