C++学习之数组

本文通过一个C++示例程序详细介绍了构造函数和赋值操作在C++中的应用,包括无参构造函数、带参数构造函数、拷贝构造函数及赋值运算符的重载,并解释了它们在不同场景下的作用。

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

Dog.h

#ifndef __test_header__Dog__
#define __test_header__Dog__

#include <stdio.h>
#include <string>

class Dog{
public:
    Dog();
    Dog(const char name[]);
    const Dog& operator=(const Dog &dog) const;
    bool operator==(const Dog &dog) const;
    Dog(const Dog &dog);
    std::string getName();
private:
    std::string name;
};
#endif

Dog.cpp

#include "Dog.h"
#include <iostream>

using namespace std;

Dog::Dog(){
    cout<<"Dog()"<<endl;
};

Dog::Dog(const char name[]) {
    cout<<"Dog(const char name[])"<<endl;
    this->name = name;
    cout << this->name << endl;
};

Dog::Dog(const Dog &dog){
    this->name = dog.name;
    cout<<"Dog(const Dog &dog)"<<endl;
};

bool Dog::operator==(const Dog &dog) const {
    return dog.name == this->name;
};

const Dog& Dog::operator=(const Dog &dog) const {
    cout<<"operator="<<endl;
    return *this;
};

string Dog::getName(){
    return this->name;
};

main.cpp

#include <iostream>
#include <string>
#include <vector>
#include "Dog.h"

using namespace std;

int main(int argc, const char * argv[]) {
    Dog dog("haha");
    Dog dogs[2];
    dogs[0] = dog;
    dogs[1] = dog;
    cout << dogs[0].getName() << endl;
    return 0;
}
输出如下:


可以看到数组在声明时会根据数组指定的大小去调用无参的拷贝构造函数构造出Dog数组中得元素,然后在复制时会调用重写后的=运算符来实现赋值操作,如果没有重载=运算符,则执行的是默认的按位拷贝操作。

如果将数组改为列表初始化的方式,如下:

Dog dogs[2] = {"haha", "sasa"};
那么数组的构造将调用带参数类型的构造函数来构造数组。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值