操作符的重载以及数组/vector对象的初始化

本文通过一个具体的C++示例详细介绍了运算符重载、构造函数及拷贝构造函数的工作原理。展示了如何定义一个简单的类,并实现基本的赋值运算符重载和类型转换运算符,同时观察了对象数组与向量容器中不同构造过程的表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

>> cat operator.C 
#include <iostream>
#include <vector>
using namespace std;

class A
{
public:
        A(int i = 0):a(i)
        {
                cout << " I am in A() " << endl;
        }
        A(const A &x)
        {
                cout << " I am in A(const A&) " << endl;
                a=x.a;
        }
        A& operator=(int i)
        {
                cout << " I am in operator() " << endl;
                a=i;
                return *this;
        }
        operator int()
        {
                cout << " I am in operator int() " << endl;
                return a;
        }
private:
        int a;
};

int main()
{
        A a =3;

        a=4;

        int x = a;
        cout << x << endl;

        cout << "test array of A " << endl;
        A a1[10];

        cout << "test vector of A " << endl;
        vector<A> v(10);
}

运行结果:

>> ./a.out
 I am in A() 
 I am in operator() 
 I am in operator int() 
4
test array of A 
 I am in A() 
 I am in A() 
 I am in A() 
 I am in A() 
 I am in A() 
 I am in A() 
 I am in A() 
 I am in A() 
 I am in A() 
 I am in A() 
test vector of A 
 I am in A() 
 I am in A(const A&) 
 I am in A(const A&) 
 I am in A(const A&) 
 I am in A(const A&) 
 I am in A(const A&) 
 I am in A(const A&) 
 I am in A(const A&) 
 I am in A(const A&) 
 I am in A(const A&) 
 I am in A(const A&) 

对象数组:调用default constructor来初始化每个对象

vector:先调用default constructor生成一个临时对象,然后调用拷贝构造函数来初始化每个元素。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值