c++ 标准类的定义

1.新建控制台工程

2 添加Person类 

#pragma once
#include <string>

using namespace std;

class Person
{
public:
	Person();
	Person(string xn, int n = 0);
	Person(Person& someone);
	~Person();
	void display() const;
protected:
	string name;
	int friendcount;
	string* friendlist;
};

#include "Person.h"
#include <iostream>
using namespace std;

Person::Person()
{
	friendlist = NULL;
}

Person::Person(string xn, int n)
{
	name = xn;
	cout << "welecome person " << name << endl;
	friendcount = n;
	if (friendcount>0)
	{
		cout << "you have " << friendcount << " friends" << ".Who are they?" << endl;
		string* p = friendlist = new string[n];
		while (n > 0)
		{
			cin >> *p;
			p++;
			n--;
		}
	}
	else
	{
		friendlist = NULL;
	}

}

Person::Person(Person& someone)
{
	name = someone.name;
	friendcount = someone.friendcount;
	cout << "welcome a duplicated person " << name << endl;
	if (friendcount>0)
	{
		int n = friendcount;
		cout << "you have " << friendcount << " friends" << ".Who are they?" << endl;
		string* p = friendlist = new string[n];
		while (n > 0)
		{
			cin >> *p;
			p++;
			n--;
		}
	}
	else
	{
		friendlist = NULL;
	}
}

Person::~Person()
{
	cout << "byte~" << endl;
	delete[] friendlist;
}

void Person::display() const
{
	cout << "Hi~" << name << endl;
	int n = friendcount;
	if (n<0)
	{
		cout << "you have 0 friend" << endl;
	}
	else
	{
		cout << "Your friends are :";
		string* p = friendlist;
		while (n>0)
		{
			cout << *p << ' ';
			p++;
			n--;
		}
		cout << endl;
	}
}

3 主程序 

// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

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

int main()
{
    Person p1("wang");
    p1.display();
    Person p2("zhang", 2);
    p2.display();
    Person* p3 = new Person(p2);
    p3->display();
    delete p3;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/dxm809/article/details/114298432