C++中的常成员函数定义,
常成员函数
在类中,可以使用const这个保留字来保护成员数据不被成员函数改写。
我们把这种成员函数称为常成员函数。
int getWeight() const;
构造函数跟java挺类似的,很好理解。
class Person{
public:
Person();
}
构造函数定义与调用时机。
构造函数重载的作用
代码
Person.h
1 // 2 // Person.h 3 // ArrayTest 4 // 5 // Created by 张学院 on 14-1-8. 6 // Copyright (c) 2014年 com.mix. All rights reserved. 7 // 8 9 //防止重复引用 10 #ifndef __ArrayTest__Person__ 11 #define __ArrayTest__Person__ 12 13 #include <iostream> 14 using namespace std; 15 class Person{ 16 //---------成员变量-------- 17 public : 18 19 int age; 20 21 private : 22 int weight; 23 char name[30]; 24 char sex; 25 //---------成员方法-------- 26 public: 27 //----构造函数------- 28 Person(); 29 //-----构造函数重载----- 30 Person(int age); 31 32 void setWeight(int weight); 33 int getWeight() const; 34 //char * getName() const; 35 //const 指针,保证指针不被修改 36 const char * getName() const; 37 38 void info() const; 39 }; 40 #endif /* defined(__ArrayTest__Person__) */
Person.cpp
1 // 2 // Person.cpp 3 // ArrayTest 4 // 5 // Created by 张学院 on 14-1-8. 6 // Copyright (c) 2014年 com.mix. All rights reserved. 7 // 8 9 #include "Person.h" 10 //------方法实现格式------ 11 //----返回值 类::方法名 (参数)------ 12 void Person::setWeight(int weight){ 13 //-----this 代表 14 this->weight=weight; 15 } 16 //--------const 编译限制------- 17 int Person::getWeight() const{ 18 //weight++;报错 19 return weight; 20 } 21 const char * Person::getName() const{ 22 23 return name; 24 25 } 26 27 void Person::info() const{ 28 29 printf("%s %d %c %d ",name,age,sex,weight); 30 } 31 //--------构造函数:初始化成员变量------------ 32 Person::Person(){ 33 printf("call the functon Person() "); 34 strcpy(name, "a man"); 35 weight=60; 36 age=20; 37 sex='m'; 38 } 39 //--------构造函数:重载------------ 40 Person::Person(int age){ 41 printf("call the functon Person(int age) "); 42 strcpy(name, "a man"); 43 weight=60; 44 this->age=age; 45 sex='m'; 46 47 }
main.cpp
1 // 2 // main.cpp 3 // ArrayTest 4 // 5 // Created by 张学院 on 14-1-6. 6 // Copyright (c) 2014年 com.mix. All rights reserved. 7 // 8 9 #include <iostream> 10 11 #include <string> 12 #include "Person.h"; 13 int main() 14 { 15 //----栈分配---- 16 //-----对象分配内存之后就会调用构造函数------- 17 Person per; 18 //strcpy(name, "iphone");报错 19 per.info(); 20 21 //-------显示调用构造函数,如果写构造函数,系统会默认构造函数,所有的值为0-------- 22 //-------只有显示调用构造函数,才会调用系统会默认构造函数-------- 23 Person per1= Person(); 24 25 26 //-----堆分配---- 27 Person *per2= new Person(); 28 //-----指针调用方法-> ------- 29 per2->info(); 30 delete per2; 31 32 33 Person *per3= new Person(40); 34 per3->info(); 35 delete per3; 36 return 0; 37 }
输出:
call the functon Person()
a man
20
m
60
call the functon Person()
call the functon Person()
a man
20
m
60
call the functon Person(int age)
a man
40
m
60