C++自动类型转化--特殊构造函数方法和重载的运算符方法

一、重载运算符法

#include <stdio.h>
#include <iostream>

class Three
{
    int i;
public:
    Three(int ii = 0, int = 0) : i(ii) 
    {
        std::cout << "you call Three()" << std::endl;
    }
};


class Four
{
    int x;
public:
    Four(int xx) : x(xx) {}
    operator Three() const { return Three(x);}
};

void g(Three) {}
int main()
{
    Four four(1);
    g(four);
    g(1);//calls Three(1,0)
    int n;
    std::cin >> n;
}
//输出两次:
you call Three()

2.构造函数转换

//这个构造函数能够把另一类型的对象(引用)作为它的单个参数,那么构造函数允许编译器执行自动类型转换;
#include <stdio.h> #include <iostream> class One { public: One() {} }; class Two { public: Two(const One&) { std::cout << "you call Two()" << std::endl; } }; void f(Two) {} int main() { One one; f(one);//wants a Two ,has a one
//输出:
"you call Two()”
    int i;
    std::cin >> i;
}
注意:以上方法调用了Two的隐藏的构造函数,如果关心调用效率的话不要这样使用!

3.阻止构造函数被隐式调用,要求必须显示调用:

//使用关键词explicit时,必须显示调用,完成类型转换
#include <stdio.h> #include <iostream> using namespace std; class One { public: One() { } }; class Two { public: explicit Two(const One&) {} }; void f(Two) {} int main() { One one; //!f(one);//NO auto conversion allowed f(Two(one)); //int i; //cin >> i; }
怕什么真理无穷,进一寸有一寸的欢喜。---胡适
原文地址:https://www.cnblogs.com/hujianglang/p/7255746.html