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;
}