zoukankan      html  css  js  c++  java
  • 关于C++的疑问剖析

    1)众所周知,抽象类是不存在对象的,只提供接口而不提供实现。但是抽象类能不能作为一个类指针,指向其子类的对象呢?

    class Interface {
        public:
        virtual void fun() = 0;
    };
    
    class Implement: public Interface {
    public:
        void fun() {
            cout<<"This is Implement object."<<endl;
        }
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        Interface *obj = new Implement();
        obj->fun();
        return 0;
    }

      结论:能。抽象类不能拥有自己的类对象,但是,可以定义抽象类指针指向其子类的对象。

    2)指向指针的指针  两种最常见的情形:(数组的名字会退化成其首元素的指针。

    2.1 指针数组:

    class Shape {
    public:
        void testFunc() {
            cout<<"Shape::testFunc()"<<endl;
        }
        //...
    };
    
    Shape *picture[10];
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        Shape **temp = picture;
        Shape *p = *temp;
        p->testFunc();
        return 0;
    }

    2.2 

    void scanTo(const char **p, char ch) {
        while (**p && **p != ch) {
            ++*p;
        }
    }
    int _tmain(int argc, _TCHAR* argv[])
    {
        char s[] = "hello, World";
        const char *cp = s;
        scanTo(&cp, ',');//将指针cp移动第一个“,”出现的位置
        cout<<*cp<<endl;
        return 0;
    }

    3)仿函数

    //仿函数 加法
    template <class T>
    struct plus {
        T operator() (const T& x, const T& y) const {
            return x+y;
        }
    };
    
    //仿函数 减法
    template <class T>
    struct minus {
        T operator() (const T& x, const T& y) const {
            return x-y;
        }
    };
    
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        //以下产生仿函数对象
        plus<int> plusObj;
        minus<int> minusObj;
        //以下使用仿函数,就像使用一般函数一样
        cout<<plusObj(3,5)<<endl;
        cout<<minusObj(3,5)<<endl;
    
        //以下直接产生仿函数的临时对象(第一对小括号),并调用之(第二对小括号)
        cout<<plus<int>()(3,5)<<endl;
        cout<<minus<int>()(3,5)<<endl;
        return 0;
    }
  • 相关阅读:
    linux nohup
    并发编程-多进程模块介绍
    并发编程-多进程
    网络编程-粘包现象
    Typora快捷键Mac
    网络编程
    异常处理
    面向对象-元类介绍
    面向对象-内置方法
    面向对象-反射
  • 原文地址:https://www.cnblogs.com/wiessharling/p/4782324.html
Copyright © 2011-2022 走看看