C++基础之this指针(八)

本文详细解释了C++中的this指针如何指向对象本身,以及静态成员函数的定义、区别于非静态成员函数的特点,同时讨论了静态数据成员的初始化和静态成员函数的调用方式。
摘要由CSDN通过智能技术生成

关于this指针首先它存在与类中每个非静态函数里,指向对象本身并且不能被修改是一个指针常量,类似python中的self,用它来标记每个不同对象。

class Foo(object):
    def __init__(self,name):
        self.name=name

    def obj_func(self):
        print('实例方法')

    @staticmethod
    def static_func():
        print('静态方法')

静态成员函数

在C++中我们通过static关键字来定义静态成员函数,首先再看静态成员函数之前我们先看一下静态数据成员。在c++中我们在类中定义静态数据成员是放在全局静态区,并不占用对象的空间,需要注意的是我们在初始化静态成员变量时不能在初始化列表中进行初始化

class Computer
{
public:




private:
	int _price;
	char* _name;
	static int _total;
};
int Computer::_total = 0;

在初始化静态数据成员时我们需要在全局静态的位置并且加上类名和作用域限定符的形式。

此时我们再来看静态成员函数

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>


using namespace std;

class Computer
{
public:
	Computer(const char * name,int price)
		:_name(new char[strlen(name)+1]())
	{

		_price = price;
		cout << "Computer构造函数" << endl;
		strcpy(_name, name);
		_total += price;
	}

	Computer(const Computer& rhs)
		:_name(new char[strlen(rhs._name) + 1]())
	{
		_price = rhs._price;
		cout << "Computer拷贝构造函数" << endl;
		strcpy(_name, rhs._name);
	}
	void set_Price(int price) 
	{
	 this->_price = price;
		
	}

	void set_Brand(const char* name) 
	{
		strcpy(_name, name);
	}
	//赋值运算函数
	Computer& operator=(const Computer& com)
	{ 
		if (this != &com)
		{
			//内存泄漏问题
			delete[] this->_name;
			_name = nullptr;
			//解决double free用深拷贝
			_name = new char[strlen(com._name) + 1]();
			cout << "Computer &operator=()" << endl;
			this->_price = com._price;
			//_name = com._name;
			strcpy(_name, com._name);
		}

		return *this;
		
	}
	static void printTotalPrice()
	{
		cout << "静态成员函数" << endl;
		cout << "总价=" << _total << endl;
	}
	void print()
	{
		cout << "name" << _name << endl;
		cout << "price" << _price << endl;
	}


	~Computer()
	{
		cout << "析构函数" << endl;
		if(_name != nullptr)
		{ 
			delete[] _name;
			_name = nullptr;
		}
	}
private:
	int _price;
	char* _name;
	static int _total;
};
int Computer::_total = 0;

void test1() 
{
	Computer com("Lenovo", 1500);
	com.print();

	cout << endl << endl;
	com.printTotalPrice();

	Computer com1("Thinkipad",2000);
	com1.print();
	cout << endl << endl;
	Computer::printTotalPrice();


}

int main()
{
	test1();
}

可以看出在静态成员函数,由于没有this指针我们并不可以在静态成员函数中调用对象中其他的非静态成员函数和非静态数据成员,这个可以类比python中的静态方法。当在非静态成员函数调用静态成员函数时也需要加上类名和作用域限定符。在类外调用静态成员函数时有两种方法,一种是通过对象调用另一种是通过类名和作用域限定符的形式。

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值