一开始的时候是将函数定义放在类里面的。
现在类里面只放函数的声明,在类的外面实现函数的定义。
#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.name = "zhangsan";
per.setName("zhangsan");
per.setAge(200);
per.printInfo();
return 0;
}
一个工程由两个人来实现,A来实现这个类,而B这个人只关心这个类怎么用。
A:实现Person类,A应该提供两个文件person.h给B使用,一个是person.cpp实现这个类
B:实现main函数,B只关心怎么用Person这个类。直接#include <person.h>即可
所以工程中应该包含三个文件:main.cpp person.cpp person.h
person.h(只包含这个类的声明)
namespace B{
class Person {
private:
char *name;
int age;
char *work;
public:
void setName(char *name);
int setAge(int age);
void setWork(char *work);
void printInfo(void);
};
void printVersion(void);
}
person.cpp(包含类中函数成员的具体实现)
/*使用双引号表明先到当前目录下去寻找这个头文件*/
#include "person.h"
#include <stdio.h>
namespace B{
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::setWork(char *work)
{
this->work = work;
}
void Person::printInfo(void)
{
printf("name = %s, age = %d, work = %s\n", name, age, work);
}
void printVersion(void)
{
printf("write by mai V2\n");
}
}
main.cpp(实现主要的逻辑功能)
#include <stdio.h>
#include "person.h"
int main(int argc, char *argv[])
{
Person per;
per.setName("zhangsan");
per.setAge(10);
per.setWork("student");
per.printInfo();
}
/*然后利用makefile管理这个工程*/
注意:利用g++编译源文件.cpp生成目标文件.o要带-c参数
person : main.o person.o
g++ $^ -o $@
%.o : %.cpp
g++ $< -c -o $@
clean:
rm -f *.o person
假设团队进来一个新人C,他要实现一个Dog类,要包含两个文件
dog.cpp包含类的函数成员的实现:
dog.h包含类的声明
/*dog.h*/
namespace C{
class Dog{
private:
char *name;
int age;
public:
void setName(char *name);
int setAge(int age);
void printInfo(void);
};
void printVersion(void);
}
/*dog.cpp*/
/*使用双引号表明先到当前目录下去寻找这个头文件*/
#include "dog.h"
#include <stdio.h>
namespace C
{
void Dog::setName(char *name)
{
this->name = name;
}
int Dog::setAge(int age)
{
if (age < 0 || age > 20)
{
this->age = 0;
return -1;
}
this->age = age;
return 0;
}
void Dog::printInfo(void)
{
printf("name = %s, age = %d\n", name, age);
}
void printVersion(void)
{
printf("write by mai V1\n");
}
}
当一个工程中可能包含两个返回值类型相同,函数名相同,参数相同的函数。这两个相同的函数可能是由两个不同的人写的。这时候就要用命名空间了
用法namespace C{
在这里面写函数的实现
}
使用命名空间的方法有
1、C::函数名/类名;
2、using C::函数名/类名; /*一个一个导入*/
3、using namespace C; /*命名空间的全部内容直接导入*/
命名空间的作用:防止函数重名
C++中
1、stdio.h头文件换为iostream
2、打印的时候printf换为cout<<,endl是回车换行。要使用命名空间using namespace std;