一:
01.cpp
#include <stdio.h>
class Person{
private:
char *name;
int age;
char *work;
public:
void setName(char *name) //就近原则,如果不写this->name,那么name指的就是本函数中的name
{
this->name = name; //this->name 当前对象的name
}
int setAge(int age)
{
if (age < 0 || age > 150)
{
this->age = 0;
return -1;
}
this->age = age;
return 0;
}
void printInfo(void)
{
printf("name = %s, age = %d, work = %s\n", name, age, work);
}
};
int main(int argc, char **argv)
{
Person per;
per.setName("zhangsan");
per.setAge(200);
per.printInfo();
per.setName("lisi");
per.setAge(100);
per.printInfo();
return 0;
}
二:
对程序结构进行优化1:
02.cpp
#include <stdio.h>
class Person{
private:
char *name;
int age;
char *work;
public:
void setName(char *name);
int setAge(int age);
void printInfo(void);
};
void Person::setName(char *name)
{
this->name = name;
}
int Person::setAge(int age)
{
if (age < 0 || age > 150)
{
this->age = 0;
return -1;
}
this->age = age;
return 0;
}
void Person::printInfo(void)
{
printf("name = %s, age = %d, work = %s\n", name, age, work);
}
int main(int argc, char **argv)
{
Person per;
per.setName("zhangsan");
per.setAge(200);
per.printInfo();
per.setName("lisi");
per.setAge(100);
per.printInfo();
return 0;
}
三:
对程序进行优化2:
person.h只需要告诉main.cpp有哪些函数
//perosn.h
#include <stdio.h>
class Person{
private:
char *name;
int age;
char *work;
public:
void setName(char *name);
int setAge(int age);
void printInfo(void);
};
person.cpp只需要实现这些函数
//person.cpp
#include <stdio.h>
#include "person.h"
void Person::setName(char *name)
{
this->name = name;
}
int Person::setAge(int age)
{
if (age < 0 || age > 150)
{
this->age = 0;
return -1;
}
this->age = age;
return 0;
}
void Person::printInfo(void)
{
printf("name = %s, age = %d, work = %s\n", name, age, work);
}
main.cpp
//main.cpp
#include <stdio.h>
#include "person.h"
int main(int argc, char **argv)
{
Person per;
per.setName("zhangsan");
per.setAge(200);
per.printInfo();
per.setName("lisi");
per.setAge(100);
per.printInfo();
return 0;
}
再加上一个Makefile文件
person: main.o person.o
g++ -o $@ $^
%.o : %.cpp
g++ -c -o $@ $<
clean:
rm -f *.o person