示例程序
// ---CodeBlob.h---
#ifndef CODEBLOB_H_
#define CODEBLOB_H_
class CodeBlob {
private:
const char* _name;
int _size;
public:
CodeBlob();
void printName();
void printSize();
void setSize(int size);
virtual ~CodeBlob();
};
#endif /* CODEBLOB_H_ */
// ---CodeBlob.cpp---
#include <iostream>
#include "CodeBlob.h"
typedef unsigned char u_char;
typedef u_char* address;
CodeBlob::CodeBlob() {
_size = 5;
_name = "hello";
}
CodeBlob::~CodeBlob() {
}
void CodeBlob::printName(){
std::cout << _name << std::endl;
}
void CodeBlob::printSize(){
std::cout << _size << std::endl;
address aa = (address)this; // 这样写是没语法错误的
std::cout << aa << std::endl;
}
void CodeBlob::setSize(int size){
_size = size;
}
// ---PointerConvert.cpp---
#include <iostream>
#include "CodeBlob.h"
int main(int argc, char **argv) {
std::cout << "hello simon"<<std::endl;
CodeBlob cb1;
CodeBlob cb2;
CodeBlob* cb3 = new CodeBlob();
cb1.printName();
cb1.setSize(100);
cb1.printSize();
cb2.printSize();
cb3->setSize(20);
cb3->printSize();
// address a = (address)cb3;
// std::cout << a <<std::endl;
return 0;
}
此处是可以将对象this转换成unsigned char指针的。adress的值就是对象this的地址。