类的定义,对象的创建销毁,拷贝构造函数,赋值=运算符,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;
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;
}
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 [] _brand;
_brand = nullptr;
_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;
}
void Computer::printTotalPrice()
{
cout << "totalPrice:" << _totalPrice << endl;
}
void Computer::print()
{
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;
}