C++ 类模板实例化对象,向函数传参的方式

2022-05-09 16:15:51 浏览数 (1)

C 类模板实例化对象,向函数传参的方式一共有3种:

  • 指定传入的类型:直接显示对象的数据类型;
代码语言:javascript复制
#include<iostream>
#include<string>
using namespace std;

template<class T1, class T2>
class Demo{
public:
    T1 s_name;
    T2 i_age;
    Demo(T1 name, T2 age);
    void show(){
        cout<<"Name: "<< s_name <<"nAge: "<<i_age<<endl;
    }
};

template<class T1, class T2>
Demo<T1, T2>::Demo(T1 name, T2 age):s_name(name),i_age(age){}

void print_demo(Demo<string, int> &d){
    d.show();
}

void test(){
    Demo<string, int> d("孙悟空", 500000);
    print_demo(d);
}

int main(){
    test();
    return 0;
}
  • 参数模板化:将对象中的参数变为模板进行传递;
代码语言:javascript复制
#include<iostream>
#include<string>

using namespace std;

template<class T1, class T2>
class Demo {
public:
    T1 s_name;
    T2 i_age;

    Demo(T1 name, T2 age);

    void show() {
        cout << "Name: " << s_name << "nAge: " << i_age << endl;
    }
};

template<class T1, class T2>
Demo<T1, T2>::Demo(T1 name, T2 age):s_name(name), i_age(age) {}

template<class T1, class T2>
void print_demo(Demo<T1, T2> &d) {
    d.show();
    cout << "T1的类型: " << typeid(T1).name() << endl;
    cout << "T2的类型: " << typeid(T2).name() << endl;
}

void test() {
    Demo<string, int> d("唐僧", 5000);
    print_demo(d);
}

int main() {
    test();
    return 0;
}
  • 整个类模板化:将对象类型模板化进行传递。
代码语言:javascript复制
#include<iostream>
#include<string>

using namespace std;

template<class T1, class T2>
class Demo {
public:
    T1 s_name;
    T2 i_age;

    Demo(T1 name, T2 age);

    void show() {
        cout << "Name: " << s_name << "nAge: " << i_age << endl;
    }
};

template<class T1, class T2>
Demo<T1, T2>::Demo(T1 name, T2 age):s_name(name), i_age(age) {}

template<class T>
void print_demo(T &d) {
    d.show();
    cout << "T的类型: " << typeid(T).name() << endl;
}

void test() {
    Demo<string, int> d("貂蝉", 50);
    print_demo(d);
}

int main() {
    test();
    return 0;
}

以上3种参数传入方式最常用的是:指定传入的类型。

0 人点赞