C++中的构造函数

来源:互联网 发布:java.util.zip 加密 编辑:程序博客网 时间:2024/06/16 08:06
    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;


0 0