/* Human.h */
#include <string>
/*
* this指當前對象的地址
*/
class Human
{
private:
char* name;
public:
Human(const char* initString); //變量若不允許函數修改,最好定義成const變量
~Human();
void getObjName();
};
/*Human.cpp*/
#include <iostream>
#include <string>
#include <string.h>
#include "Human.h"
void Human::getObjName()
{
printf("1 this = 0x%x\n", this); //此對象的地址
}
Human::Human(const char* initString)
{
std::cout << "2 call Human()" << std::endl;
name = new char[strlen(initString) + 1];
}
/*析構函數(對象被銷燬時被調用,類只有一個析構函數*/
Human::~Human()
{
std::cout << "3 call ~Human()" << std::endl;
}
#include <iostream>
#include "Human.h"
int main()
{
Human* man = new Human("aaaa"); //此處第一次調用構造函數
printf("man addr = 0x%x\n", man); //打印對象的地址,跟對象內部的this是同一個值
man->getObjName();
delete man;
return 0;
}
輸出:
2 call Human()
man addr = 0x62b918 //兩個地址一樣,表面this爲對象地址
1 this = 0x62b918
3 call ~Human()