c++学习:01

类的定义,对象的创建销毁,拷贝构造函数,赋值=运算符,this指针,static成员……

#include <stdio.h>
#include <string.h>
#include <iostream>

using std::cout;
using std::endl;

class Computer
{
public://公有成员函数,作为对外接口
	Computer(const char *brand, float price);//构造函数
	Computer(const Computer &rhs);//拷贝构造函数
	Computer & operator=(const Computer & rhs);//重载=赋值运算符
	void setBrand(const char *brand);
	void setPrice(float price);
	static void printTotalPrice();
	void print();
	~Computer();//析构函数

private:
	char *_brand;
	float _price;
	static float _totalPrice;
};

float Computer::_totalPrice = 0;//static静态数据成员,在类外定义,位于全局区

Computer::Computer(const char *brand, float price) //类外定义,构造函数
: _brand(new char[strlen(brand) + 1]()) //堆空间,数据成员
, _price(price)
{
	cout << "Computer(const char *brand, float price)" << endl;
	strcpy(_brand, brand);
	_totalPrice += _price;//测试static数据成员
}
Computer::Computer(const Computer & rhs)                                                   
: _brand(new char[strlen(rhs._brand) + 1]())//拷贝构造函数默认是浅拷贝
, _price(rhs._price)
{
	cout << "Computer(const Computer &rhs)" << endl;
	strcpy(_brand, rhs._brand);
}

Computer & Computer::operator=(const Computer & rhs)
{
	cout << "operator = ()" << endl;
	if(this != &rhs)//避免自复制问题,执行delete后出错
	{
		delete [] _brand;//释放左操作数,原空间可能不够用,内存越界
		_brand = nullptr;//释放空间即置为null,习惯
		_brand = new char[strlen(rhs._brand) + 1]();//深拷贝
		strcpy(_brand, rhs._brand);
		_price = rhs._price;
	}
	return *this;//返回对象本身,可链式编程
}

void Computer::setBrand(const char *brand)
{
	strcpy (_brand, brand);
}

void Computer::setPrice(float price)
{
	_price = price;
}

//静态成员函数不包含this指针
void Computer::printTotalPrice()//定义时,不必再写static,会报错
{
	cout << "totalPrice:" << _totalPrice << endl;
}

void Computer::print()  //隐含的this指针,this->price
{
	printf("brand = %p\n",_brand);
	printf("price = %p\n",&_price);
	cout << "brand = " << _brand << endl;
	cout << "price = " << _price << endl;
}

Computer::~Computer()  //析构函数
{
	cout << "~Computer()" << endl;
	if(_brand)
	{
		delete [] _brand;
		_brand = nullptr;
	}
	_totalPrice -= _price;
}

void test1()
{
	cout << "sizeof(Computer) = " << sizeof(Computer) << endl;
	Computer com1("ThinkPad", 10000);
	cout << "com1 = ";
	com1.print();

	Computer::printTotalPrice();//静态成员函数,可以通过类名访问

	Computer com2 = com1;
	cout << "com2 = ";
	com2.print();

	com2.setPrice(7000);
	com2.setBrand("Huawei");

	com1 = com2;
	com1.print();
	com2.print();
}

int main(int argc, char **argv)
{
	test1();
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值