C++结构

Hello, 大家好,我是爱吃香蕉的猴子,写写C++中的结构


#define _CRT_SECURE_NO_WARNINGS

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

using namespace std;

class Person {

private:
	char* name;
	int age;
	char* work;

public:

	Person() {
		cout << "Person()" << endl;
		name = NULL;
		work = NULL;
	}

	Person(char* name)
	{
		this->name = new char[strlen(name) + 1];
		strcpy(this->name, name);
		this->work = NULL;
	}

	Person(char* name, int age, const char* work = "none")
	{
		cout << "Person, name = " << name << ", age = " << age << endl;
		this->age = age;
		this->name = new char[strlen(name) + 1];
		strcpy(this->name, name);
		this->work = new char[strlen(work) + 1];
		strcpy(this->work, work);
	}

	Person(Person &per)
	{
		cout << "Person" << endl;
		this->age = per.age;
		this->name = new char[strlen(per.name) + 1];
		strcpy(this->name, per.name);
		this->work = new char[strlen(per.work) + 1];
		strcpy(this->work, per.work	);
	}

	~Person()
	{
		cout << "~Person()" << endl;
		if (this->name)
		{
			cout << "name = " << name << endl;
			delete this->name;
		}
		if (this->work)
		{
			cout << "work=" << work << endl;
			delete this->work;
		}
	}

	void setName(char* n)
	{
		name = n;
	}

	int setAge(int a)
	{
		if (a < 0 || a > 150)
		{
			age = 0;
			return -1;
		}
		age = a;
		return 0;
	}

	void printInfo(void)
	{
		cout << "name = " << name <<", age =" << age << ", work =" << work << endl;
	}

};


class Student {
private:
	Person father;
	Person mother;
	int student_id;

public:
	Student()
	{
		cout << "Student()" << endl;
	}

	Student(int id, char* father, char* mother, int father_age = 40, int mother_age = 39) : 
		mother(mother, mother_age), father(father, father_age)
	{
		cout << "Student(int id, char *father, char *mother, int father_age = 40, int mother_age = 39)" << endl;
	}

	~Student()
	{
		cout << "~Student()" << endl;
	}
};


int main(int argc, char** argv)
{
	string str1 = "bill";
	string str2 = "lily";
	const char* charP = str1.c_str();
	const char* charC = str2.c_str();
	char* name1 = const_cast<char*>(charP);
	char* name2 = const_cast<char*>(charC);

	Student s(1, name1, name2);
	return 0;
}

                                         Code的搬运工V1.0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值