您的位置:首页 > 编程语言 > C语言/C++

c++知识学习 (1)

2014-01-08 17:44 323 查看
C++中的常成员函数定义,

常成员函数

在类中,可以使用const这个保留字来保护成员数据不被成员函数改写。

我们把这种成员函数称为常成员函数。

int getWeight() const;

构造函数跟java挺类似的,很好理解。

class Person{

public:

Person();

}

构造函数定义与调用时机。

构造函数重载的作用

代码

Person.h

//
//  Person.h
//  ArrayTest
//
//  Created by 张学院 on 14-1-8.
//  Copyright (c) 2014年 com.mix. All rights reserved.
//

//防止重复引用
#ifndef __ArrayTest__Person__
#define __ArrayTest__Person__

#include <iostream>
using namespace std;
class Person{
//---------成员变量--------
public :

int age;

private :
int weight;
char name[30];
char sex;
//---------成员方法--------
public:
//----构造函数-------
Person();
//-----构造函数重载-----
Person(int age);

void setWeight(int weight);
int getWeight() const;
//char * getName() const;
//const 指针,保证指针不被修改
const char * getName() const;

void info() const;
};
#endif /* defined(__ArrayTest__Person__) */


Person.cpp

//
//  Person.cpp
//  ArrayTest
//
//  Created by 张学院 on 14-1-8.
//  Copyright (c) 2014年 com.mix. All rights reserved.
//

#include "Person.h"
//------方法实现格式------
//----返回值 类::方法名 (参数)------
void Person::setWeight(int weight){
//-----this 代表
this->weight=weight;
}
//--------const 编译限制-------
int  Person::getWeight() const{
//weight++;报错
return weight;
}
const char * Person::getName() const{

return name;

}

void Person::info() const{

printf("%s\n%d\n%c\n%d\n",name,age,sex,weight);
}
//--------构造函数:初始化成员变量------------
Person::Person(){
printf("call the functon Person()\n");
strcpy(name, "a man");
weight=60;
age=20;
sex='m';
}
//--------构造函数:重载------------
Person::Person(int age){
printf("call the functon Person(int age)\n");
strcpy(name, "a man");
weight=60;
this->age=age;
sex='m';

}


main.cpp

//
//  main.cpp
//  ArrayTest
//
//  Created by 张学院 on 14-1-6.
//  Copyright (c) 2014年 com.mix. All rights reserved.
//

#include <iostream>

#include <string>
#include "Person.h";
int main()
{
//----栈分配----
//-----对象分配内存之后就会调用构造函数-------
Person per;
//strcpy(name, "iphone");报错
per.info();

//-------显示调用构造函数,如果写构造函数,系统会默认构造函数,所有的值为0--------
//-------只有显示调用构造函数,才会调用系统会默认构造函数--------
Person per1= Person();

//-----堆分配----
Person *per2= new Person();
//-----指针调用方法->  -------
per2->info();
delete per2;

Person *per3= new Person(40);
per3->info();
delete per3;
return 0;
}


输出:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: