9类和对象与this指针

类和对象,this

面向对象的四大特性:抽象,封装/隐藏,继承,多态

  • 属性一般都是私有的,向外提供公有方法以访问私有属性。
  • 类本身不占内存,实例化对象占内存。
  • 类体内定义的成员函数默认为内联,体外定义需要加inline修饰。
  • 一个类可以定义无数的对象,每一个对象都有自己的成员变量,成员函数是公用的,不占对象的存储空间。
  • 那么方法被调用时,如何知道所处理的对象?方法调用时,隐式传入了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();
    }
    
posted @ 2024-01-16 10:32  SIo_2  阅读(7)  评论(0)    收藏  举报