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

c++面向对象基础

2016-01-15 15:27 381 查看
面向对象编程一般分为两个文件,头文件和源文件,例如一个Person 类,分为Person.h和Person.cpp

Person.h中有类,函数的声明:

#pragma once //该文件不会被编译多次
#include <string> //引入string
#include "Person.h"
using namespace std; //命名空间,没有这个, string也是不能用的
class Person
{
private:
int m_iAge; //命名规范,m表示member, i表示类型, 之后是变量名(pc的那个就是用的这个规范)
const string m_strName; //只读变量,定义后不可修改,可以在初始化列表中赋值
public:
Person(void);//构造函数
Person(int age);
~Person(void);//析构函数
//get set方法
string getName();
void setAge(int age);
int getAge();
};







在Person.cpp中,是类函数的实现:

#include "Person.h" //引入头文件,类方法的声明
#include <string>
#include <iostream>
using namespace std;

Person::Person(int age):m_iAge(age){//初始化列表,只能用在构造函数中,在构造函数之前执行
cout << "constructor(int age)" << endl
<< this->m_iAge << endl;
}

int Person::getAge(){
return m_iAge;
}

void Person::setAge(int age){
this->m_iAge = age;
}

string Person::getName(){
return m_strName;
}

Person::Person(void):m_iAge(18), m_strName("xxf") //初始化列表,主要用于对只读变量的赋值
{
cout << "constructor()" << endl
<< this->m_iAge << endl
<< this->m_strName << endl;
}

Person::~Person(void)
{
cout << "destroy" << endl;
}


再有一主函数的调用

#include "Person.h"
#include <iostream>
using namespace std;

int main(){

Person p1;//栈中申请内存
Person p2(15);
Person *p3 = new Person(15);//堆中申请内存
p2.setAge(16);

cout << "p1.getAge():" << p1.getAge() << endl;
cout << "p2.getAge():" << p2.getAge() << endl;
cout << "p3->getAge():" << p3->getAge() << endl;

//在栈中的变量不用手动清理内存
//在堆中的变量用手动清理内存
delete p3;
p3 = NULL;

system("pause");

return 0;
}


输出结果:



从输出可以看出:

1,构造函数和析构函数何时执行

2,在构造函数执行时,初始化列表就已经执行完毕了,变量已经有值了

3,在堆中的内存要用delete表达式清除,在栈中的内存中会在运行完后自动清除(通过debug,就可以看到在return 0; 之后会执行两次~Person())
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: