首页 > 代码库 > C++隐式转换

C++隐式转换

在C++中,隐式转换主要涉及以下情况:

1)形参对象传递

此时C++需通过临时变量将对象转换为引用后传递,如:

func(A a);
func(a);
//转换如下:
A tmp (a);
func(tmp);

2)返回值传递

A func();
//经编译器转换为:
func(A &tmp);

3) 类型隐式转换,此种情况如下:

A:A(int);
A a = 2;//调用构造函数或转换函数转换后再赋值。

综合测试程序如下:

/*
* 测试C++隐式转换
 */

#include <iostream>
using namespace std;

class A {
public:
    A():m(0) {cout << "A::A()" << endl;}
    A(int i):m(i) {cout << "A::A(int)" << endl;}
    A(const A& a) {m = a.m; cout << "A(A a)" << endl;}
    ~A() {cout << "~A::A()" << endl;}
    A operator+(int i)
    {
        return A(this->m + i);
    }
    A operator=(const A &a)
    {
        cout << "operator = " << endl;
        A b = a;
        return b;
    }
private:
    int m;
};

class B {
public :
    B() {cout << "B::B()" << endl;}
    ~B(){cout << "~B::B()" << endl;}
};

/**
 * 隐式转换有3种情况:
 * 1. 返回值与形参
 * 2.运算符重载
 * 3.类型转换
 */

A func1(A a)
{
    cout << "func1" << endl;
    return a;
}


void func2()
{
    cout << "func2" << endl;
}

int main()
{
    A a;
    A b;
    cout << "func1:" << endl;
    func1(a);
    cout << "func1(2):" << endl;
    func1(2);
    cout << "a + 2:" << endl;
    a + 2;
    cout << "end." << endl;
    return 0;
}

 

C++隐式转换