第三章 C++编程之域运算

第三章 C++编程之域运算

3.1 通过命名空间的方式在类内部声明类的方法,在类外实现对应的类方法

//以person为例:包含私有数据名字和年龄
//通过public去设置对应的名字和年龄以及打印信息
//通过命名空间的方式在类的外部去实现对应的方法
#include <stdio.h>
class Person{//类的首字母大写
private:
   char *name;
   int age;
public:
   void setName(char *name);//这里声明下
   void setAge(int age);
   void printInfo();
};
void Person::setName(char *name)//这里是实际的实现
{
   this->name = name;
}
void Person::setAge(int age)
{
   if(age<0||age>100)
   	this->age = 0;
   else
   	this->age = age;
}
void Person::printInfo()
{
   printf("name is %s,age is %d\n",this->name,this->age);
}
int main(int argc,char**argv)
{
   Person student;
   student.setName("student");
   student.setAge(10);
   student.printInfo();
   return 0;
}

3.2 将类的声明和实现方法分开

类声明的头文件

#ifndef __PERSON_H__
#define __PERSON_H__
#include <stdio.h>
class Person{//类的首字母大写
private:
	char *name;
	int age;
public:
	void setName(char *name);//这里声明下
	void setAge(int age);
	void printInfo();
};
#endif

3.3 通过域运算符实现类的方法

//以person为例:包含私有数据名字和年龄
//通过public去设置对应的名字和年龄以及打印信息
//通过命名空间的方式在类的外部去实现对应的方法
#include "person.h"

void Person::setName(char *name)//这里是实际的实现
{
	this->name = name;
}
void Person::setAge(int age)
{
	if(age<0||age>100)
		this->age = 0;
	else
		this->age = age;
}
void Person::printInfo()
{
	printf("name is %s,age is %d\n",this->name,this->age);
}

3.4 主函数定义类,并调用类的方法

#include "person.h"
int main(int argc,char**argv)
{
	Person student;
	student.setName("student");
	student.setAge(10);
	student.printInfo();
	return 0;
}

3.5 使用Makefile编译

#生成可执行文件person,依赖于文件 main.c和person.c
# 符号的意义: $@--目标文件,$^--所有的依赖文件,$<--第一个依赖文件
person:main.o person.o
	g++ -o $@ $^
%.o : %.cpp
	g++ -c -o $@ $<
	
clean:
	rm -rf *.o person

3.6 总结

通过域运算符将类的声明和实现分开,方便代码的管理和使用等
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值