隐式转换和显示转换

来源:互联网 发布:怎么样加入淘宝 编辑:程序博客网 时间:2024/06/05 14:29
#include <iostream>
using namespace std;

class A
{
public:
    A() {cout <<"constructor A()\n";}
public:
    void f()const {cout <<"A::f() is called!\n";}

};

class B {
public:
    operator A() const
        {
            return a;
        }
     A getA () { return a;}
private:
    A a;
};

void g (const A & a) {
    cout << "g(A) :" ;
    a.f();
}

int  main ( ) {

    B b;
    b.getA();

    A a;
    g (a);

    a = b.getA();

    g (b.getA() );  //使用显示转换


    g (b);  // 使用隐式转换


    return 0;
}

---------------------------------------------------------

知识点:

1、隐式转换的方法为重载 operator


    operator A() const
        {
            return a;
        }

2、必须申明为const函数才能如此调用

    g (b.getA() );

    g (b);

因为函数g的参数是引用,如果没有加上const限定符,b.getA()通过值传递返回了一个临时对象,这个临时对象是要被丢弃的,如果修改了这个对象的值,

也是要被丢弃,何必多此一举呢?我们使用的是它的方法或值,

  


原创粉丝点击