小言_互联网的博客

类似于java的Object的c++实现

304人阅读  评论(0)

java里面Object是所有对象的父类,其作为参数可以传入任何类型,c++没有该对象,不过通过qt中的源码发现,其简易实现方法,当然不像java中的Object那么万能,c++高级用法还不太会,暂时用这种记录一下:

代码如下:

param.h

//
// Created by wocan23 on 2019/9/23.
//

#ifndef TEXT_PARAM_H
#define TEXT_PARAM_H

#include <iostream>
using  namespace std;


class Param {

public:
    enum ParamType{
        STRING, INT
    };
    union Private{
        char* argS;
        int argI;
    }aPrivate;
    Param();
    Param(const string& par);
    Param(const int& par);


    int toInt() const;
    string toString()const;

    const ParamType getType()const;

private:
    ParamType paramType;
};


#endif //TEXT_PARAM_H

param.cpp

//
// Created by wocan23 on 2019/9/23.
//

#include "Param.h"

Param::Param() {

}

Param::Param(const int& par) {
    this->aPrivate.argI = par;
    this->paramType = INT;
}

Param::Param(const string& par) {
    const char * ptr = par.c_str();
    this->aPrivate.argS = (char*)ptr;
    this->paramType = STRING;
}

int Param::toInt() const{
    return this->aPrivate.argI;
}

string Param::toString() const{
    return this->aPrivate.argS;
}

const Param::ParamType Param::getType()const {
    return this->paramType;
};

main.cpp

void printInt(int a){
    cout << "int : " << a << endl;
}

void printStr(string& b){
    cout << "string : " << b << endl;
}

void testP(const Param& param){
    Param::ParamType type= param.getType();
    switch (type){
        case Param::ParamType::INT:
            printInt(param.toInt());
            break;
        case Param::ParamType::STRING:
            string str = param.toString();
            printStr(str);
            break;
    }

}

void testPS(Param param[],int count){

    for (int i = 0; i < count; ++i)
    {
        cout << "testP" << endl;
        Param pi = param[i];
        testP(pi);
    }

}

int main() {
    string a = "a";
    int b = 1;
    testP(a);
    testP(1);

    string c = "c";
    Param params[4];
    params[0] = a;
    params[1] = c;
    params[2] = b;
    params[3] = c;
    testPS(params,4);
}

发现testP方法可以传入string和int,如果想支持其他类型,那么只需要扩充联合体及相应的构造函数及成员函数


转载:https://blog.csdn.net/wocan23/article/details/101204851
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场