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