zoukankan      html  css  js  c++  java
  • C++ 面向对象 类成员函数this指针

    每个类成员函数都只涉及一个对象, 即调用它的对象。 但有时候方法可能涉及到两个对象, 在这种情况下需要使用C++ 的 this 指针

    假设将方法命名为topval(), 则函数调用stock1.topval()将访问stock1的对象数据;stock2.topval()将访问stock2的对象数据;

    如果希望该方法的两个对象进行对比, 则必须将第二个对象作为参数传递给它。这时候涉及到隐式和显式:

    top = stock1.topval(stock2);

    隐式的访问了stock1, 显示的访问了stock2, this 则代表的是 stock1, *this 则是对象指针

    // 轻松使用c++
    
    // 5. 面向对象 this指针, 面向对象的对象指针 完成
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Over {
    private:
    
    
    public:
        int h = 2;
    };
    
    
    class Stock {
    private:
        /* data */
        int h;
    public:
        Stock(int abc);
    
        ~Stock();
    
        int abc();
    
        Stock &topval(Stock &s);
    
        Stock &topval1(Over &s);
    };
    
    Stock::Stock(int abc) {
        h = abc;
        printf("%d
    ", h);
    }
    
    Stock::~Stock() {
    }
    
    int Stock::abc() {
        this->h = 10;
        printf("%d
    ", this->h);
        printf("%d
    ", h);
        return 0;
    }
    
    Stock &Stock::topval(Stock &s) {
        printf("this-h: %d, s2.h: %d
    ", this->h, s.h);
    }
    
    Stock &Stock::topval1(Over &s) {
        printf("this-h: %d, s2.h: %d
    ", this->h, s.h);
    }
    
    
    int main(int argc, char const *argv[]) {
        Stock s1(123);
        s1.abc();
    
        Stock s2(222);
        s1.topval(s2);
    
        Over s3;
        s1.topval1(s3);
    
        return 0;
    }
  • 相关阅读:
    ld: library not found for
    Could not load NIB in bundle: 'NSBundle.....
    ld: warning: directory not found for option ''
    UIRefreshControl 问题
    iOS Xcode6 新建OC Category文件
    Java 求字符串中出现频率最高字符
    Eclipse "Adb failed to restart !"
    基础练习 报时助手
    基础练习 2n皇后问题
    基础练习 Huffuman树
  • 原文地址:https://www.cnblogs.com/renfanzi/p/9178637.html
Copyright © 2011-2022 走看看