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

T t(2), T t = 2, T t = T(2)三者完全等价

T t(2), T t = 2, T t = T(2)三者完全等价

 

 

[cpp]
#include <iostream>  
#include <ostream>  
#include <string>  
using namespace std; 
class T{ 
    public: 
        T(){}; 
        T(int t) 
        { 
            cout << "复制" << endl; 
            a = t; 
        }; 
        T& operator = (const T& t) 
        { 
            cout << "赋值" << endl; 
            a = t.a; 
            return *this; 
        } 
        int a; 
}; 
int main() 

    T t(2); 
    cout << "------------------"<< endl; 
    T t1 = 2; 
    cout << "------------------"<< endl; 
    T t2 = T(2); 
    cout << "------------------"<< endl; 
    T t3; 
    t3 = t2; 
    return 0; 

#include <iostream>
#include <ostream>
#include <string>
using namespace std;
class T{
    public:
        T(){};
        T(int t)
        {
            cout << "复制" << endl;
            a = t;
        };
        T& operator = (const T& t)
        {
            cout << "赋值" << endl;
            a = t.a;
            return *this;
        }
        int a;
};
int main()
{
    T t(2);
    cout << "------------------"<< endl;
    T t1 = 2;
    cout << "------------------"<< endl;
    T t2 = T(2);
    cout << "------------------"<< endl;
    T t3;
    t3 = t2;
    return 0;
}

输出结果为:

复制
------------------
复制
------------------
复制
------------------
赋值

 

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,