当前位置:编程学习 > C/C++ >>

C++ 转换构造函数 赋值语句

一、整体代码
     Test.h
[cpp]  
#ifndef _TEST_H_  
#define _TEST_H_  
class Test  
{  
public:  
    // 如果类不提供任何一个构造函数,系统将为我们提供一个不带参数的  
    // 默认的构造函数  
    Test();  
    /*explicit */Test(int num);  
    void Display();  
    Test& operator=(const Test& other);  
    ~Test();  
private:  
    int num_;  
};  
#endif // _TEST_H_  
 
     Test.cpp
[cpp]  
#include "Test.h"  
#include <iostream>  
using namespace std;  
// 不带参数的构造函数称为默认构造函数  
Test::Test()  
{  
    num_ = 0;  
    cout<<"Initializing Default"<<endl;  
}  
Test::Test(int num)  
{  
    num_ = num;  
    cout<<"Initializing "<<num_<<endl;  
}  
Test::~Test()  
{  
    cout<<"Destroy "<<num_<<endl;  
}  
void Test::Display()  
{  
    cout<<"num="<<num_<<endl;  
}  
Test& Test::operator=(const Test& other)//参数和返回值都是引用,这样就不用调用拷贝构造函数  
{  
    cout<<"Test::operator="<<endl;  
    if (this == &other)  
        return *this;  
    num_ = other.num_;  
    return *this;//可以去掉  
}  
 
     01.cpp
[cpp]  
#include "Test.h"  
int main(void)  
{  
    Test t(10);        // 带一个参数的构造函数,充当的是普通构造函数的功能  
    t = 20;            // 将这个整数赋值给t对象  
                    // 1、调用转换构造函数将这个整数转换成类类型(生成一个临时对象)  
                    // 2、将临时对象赋值给t对象(调用的是=运算符)  
    Test t2;  
    t = t2;            // 赋值操作t.operator=(t2);即使去掉了return *this  
    return 0;  
}  
 
二、运行结果
     
三、解释
       1、Destory 20指的是消除临时的对象。
       2、转换构造函数是单个参数的构造函数,将其它类型转换为类类型。类的构造函数只有一个参数是非常危险的,因为编译器可以使用这种构造函数把参数的类型隐式转换为类类型。
       3、t = 20;首先调用转换构造函数,然后调用赋值Test& operator=(const Test& other);
             explicit说明这个函数不是转换构造函数,只是普通的构造函数。
       4、系统里面有默认的赋值运算,实现的功能和上面的赋值运算一样。
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,