C++构造函数和析构函数

private修饰的成员:只能在类内和友元中访问。

public修饰的成员:类的对象可获取。

构造函数:与类同名,不返回任何值。总是在创建对象时被调用

默认构造函数:不提供参数就可调用的构造函数。包括“带默认参数值的构造函数”。

没有默认构造函数,提供了重载的构造函数时,C++编译器不会再生成默认构造函数。

//test.h
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;

class Human {
private:
	int age;
	string name;
public:
	Human(string humansName = "Adam", int humansAge = 25);  //默认参数在头文件
};


//test.cpp
#include "class_basic.h"
Human::Human(string humansName, int humansAge) :name(humansName), age(humansAge){ 
	cout << "Construct a human called" << name;
	cout << " , " << age << " year old" << endl;
}


//main.cpp
#include<string>
#include<iostream>
#include<stdlib.h>
#include<string>
#include "test.h"
using namespace std;

int main()
{
        Human adam;
        Human eve("Eve", 18);
        system("pause");
        return 0;
}

// O:Construct a human calledAdam , 25 year old
//   Construct a human calledEve , 18 year old

 

析构函数:在对象销毁时,自动被调用,作用是释放内存。如,对象不再在作用域内 或 通过delete被删除进而被销毁 时。

析构函数不能重载,每个类都只能有一个析构函数。如果自己没定义析构函数,编译器会创建一个伪析构函数,即不释放动态分配的内存。

//test.h

#include <iostream>
#include <stdlib.h>
#include <string>
#include <string.h>
using namespace std;


class MyString {
private:
	char* buffer;
public:
	MyString(const char* initString);
	~MyString();
	int GetLen();
	const char* GetStr();
};


//test.cpp

#include "class_basic.h"


 MyString::MyString(const char* initString) {
	if (initString != NULL) {
		buffer = new char[strlen(initString) + 1];
		strcpy(buffer, initString);
		cout << "Invoking constructor" << endl;
	}
	else {
		buffer = NULL;
	}
}

MyString::~MyString() {
	cout << "Invoking destructor, clearing up" << endl;
	if (buffer != NULL) {
		delete[] buffer;
	}
}

int MyString::GetLen() {
	return strlen(buffer);
}

const char* MyString::GetStr() {
	return buffer;
}


// main.cpp

#include<string>
#include<iostream>
#include<stdlib.h>
#include<string>
#include "class_basic.h"
using namespace std;

int main()
{
	MyString mstr("hello");
	cout << mstr.GetLen() << endl;
	cout << mstr.GetStr() << endl;
	system("pause");
	return 0;
}

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值