那么方法被调用时,如何知道所处理的对象?方法调用时,隐式传入了this指针。#include <iostream>
#include<cstring>
#define MAX 10
using namespace std;
class Goods
{ //成员方法总是驼峰命名
public:
//所有成员函数在参数中默认加入this指针
Goods(char *name, double price, int amount) : _price(price), _amount(amount) {strcpy(_name, name);}
void show();
void setName(char *name) { strcpy(_name, name); }
void setPrice(double price) { _price = price; }
void setAmount(int amount) { _amount = amount; }
const char *getName(){return _name;}
double getPrice(){return _price;}
int getAmount(){return _amount;}
private:
char _name[MAX];
double _price;
int _amount;
};
void Goods::show(){
cout << "Name:" << this->getName() << endl;
cout << "Price:" << this->getPrice() <<endl;
cout << "Amount:" << this->getAmount() <<endl;
}
int main(){
Goods a("buf", 30, 200);
a.show();
}