C++中的构造函数

本文详细解析了C++中Person类的构造函数使用方法,包括默认构造函数、带有字符串参数的构造函数、带有整型参数的构造函数以及带有年龄参数的构造函数。同时纠正了一个常见的误解:即Personp2()并非构造函数调用,而是一个返回Person类型的函数。

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

    Person p1;
    Person p2();
    Person p3("张二狗");
    Person p4("张二狗", 1);
    Person p5("张二狗", 1, 20);

    p1.show();

只有4个构造函数,Person p2()并没有调用构造函数.

!!!!!!!!!!Person p2()其实是一个返回值为Person的函数,并不是初始化数据。这个书上已经说的很清楚了。。。。。

!!!!又犯错误了。。。。。


Person是个自定义的类

//Person头文件

#ifndef __COPYFUNCTION_H__
#define __COPYFUNCTION_H__

#include <string>
#include "hong.h"
class Person
{
private:
    std::string name;
    u_int number;
    u_short age;
public:
    ~Person();
    Person();
    Person(std::string name);
    Person(std::string name,u_int number);
    Person(std::string name, u_int number, u_short age);
    void show();
};
#endif

//Person cpp文件

#include "stdafx.h"
#include "copyfunction.h"
#include <iostream>
#include <string>
#include <iomanip>
#include "hong.h"
using std::cout;
using std::endl;

Person::~Person()
{
    cout << "析构函数" << endl;
}

Person::Person() :name("0.0", 0, 0)
{
    cout << "什么都不干的构造函数" << endl;
}

Person::Person(std::string s) :name(s)
{
    cout << "只构造 name 的构造函数" << endl;
}

Person::Person(std::string s, u_int n) : name(s), number(n)
{
    cout << "构造 name number 的构造函数" << endl;
}

Person::Person(std::string s, u_int n, u_short a) : name(s), number(n), age(a)
{
    cout << "构造 name number age 的构造函数" << endl;
}

void Person::show()
{
    cout.width(20);
    cout << std::right << name << endl;
    cout.width(20);
    cout << std::right << number << endl;
    cout.width(20);
    cout << std::right << age << endl;
}


//宏文件

using u_int = unsigned int;
using u_short = unsigned short;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值