轩下小酌 2021-09-09 16:53 采纳率: 100%
浏览 17
已结题

类模板对象做函数参数时为什么要用引用?

在cpp中,为什么类模板对象做函数参数时要用引用?(见void func 所在行)

#include<iostream>
using namespace std;

template<class T1,class T2>
class person
{
public:

    person(T1 a,T2 b) {

        this->m_name = a;
        this->m_age = b;
    }

    void show() {

        cout << "姓名:"<<this->m_name <<" "<<"年龄:"<<this->m_age  << endl;
    }

    T1 m_name;
    T2 m_age;
};

void func(person <string, int>&p) 

    p.show();
}

void test1()
{
    person <string, int> p1("张三", 20);
    func(p1);
}


int main() {

    test1();

    system("pause");
    return 0;
}
  • 写回答

1条回答 默认 最新

  • 轩下小酌 2021-09-09 16:54
    关注

    少了一个花括号,请见谅

    评论

报告相同问题?

问题事件

  • 系统已结题 9月17日
  • 创建了问题 9月9日