问题描述
请帮助我了解C ++中的转换运算符的工作原理。
我有一个简单的例子,我试图理解,虽然不是很清楚如何转换实际上是由编译器发生。
Please help me understand how exactly the conversion operators in C++ work.I have a simple example here which I am trying to understand, though it is not very clear how the conversion actually happens by the compiler.
class Example{
public:
Example();
Example(int val);
operator unsigned int();
~Example(){}
private:
int itsVal;
};
Example::Example():itsVal(0){}
Example::Example(int val):itsVal(val){}
Example::operator unsigned int (){
return (itsVal);
}
int main(){
int theInt = 5;
Example exObject = theInt; // here
Example ctr(5);
int theInt1 = ctr; // here
return 0;
}
推荐答案
使用调试器(和/或在每个构造函数和运算符上放置断点),以查看哪些构造函数和运算符由哪些行调用。
You can walk through that code with a debugger (and/or put a breakpoint on each of your constructors and operators) to see which of your constructors and operators is being invoked by which lines.
没有明确定义它们,编译器也为你的类创建了一个隐藏/默认拷贝构造函数和赋值运算符。
Because you didn't define them explicitly, the compiler also created a hidden/default copy constructor and assignment operator for your class. You can define these explicitly (as follows) if you want to use a debugger to see where/when they are being called.
Example::Example(const Example& rhs)
: itsVal(rhs.itsVal)
{}
Example& operator=(const Example& rhs)
{
if (this != &rhs)
{
this->itsVal = rhs.itsVal;
}
return *this;
}
这篇关于C ++中的转换运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!