指针的含义、大小及用法

含义:指向另外一种数据类型的复合类型。

大小:64位系统中,指针占8个字节

用法:

  • 指向普通对象的指针:
#include <iostream>

using namespace std;

class A {
};

int main() {
    A *p_a = new A();
    return 0;
}
  •  指向常量对象的指针
#include <iostream>

using namespace std;

int main() {
    const int a = 10;
    const int *p_a = &a;
    cout << *p_a << endl;
    return 0;
}
  • 指向函数的指针
#include <iostream>

using namespace std;

int add(int a, int b) {
    return a+b;
}

int main() {    
    int (*p_fun)(int, int);
    p_fun = add;
    cout << p_fun(1, 2) << endl;
    return 0;
}
  • 指向对象成员变量、成员函数的指针 
#include <iostream>

using namespace std;

class A {
public:
	int a;
	int b;

	int add() { return a + b; }
};

int main() {
    A ex;
	ex.a = 10;
	ex.b = 20;

	int* p_a = &ex.a;
	int (A::*p_fun)();
	p_fun = &A::add;

	cout << *p_a << endl;
	cout << (ex.*p_fun)() << endl;

    return 0;
}
  • this指针(指向类的当前对象的指针常量)
#include <iostream>
#include <cstring>

using namespace std;

class B {
private:
    int age;
    int sex;
    string name;

public:
    void set_name(string name) {this->name = name;}
    void set_age(int age) {this->age = age;}
    void set_sex(int sex) {this->sex = sex;}
    void show() {
        cout << "name:" << this->name << endl;
        cout << "age:" << this->age << endl;
        cout << "sex:" << this->sex << endl;
    }

};

int main() {
    B b;
	b.set_name("Jane");
	b.set_age(26);
	b.set_sex(0);
	b.show();

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值