关于引用&的问题

来源:互联网 发布:知乎健身教练要求 编辑:程序博客网 时间:2024/05/29 17:06
#include <iostream>using namespace std;template <class T>class A {    public:    A() {};    T g(T &a,  T &b);};template <class T>T A<T>::g(T &a, T &b){    return a + b;}int main(){    A<int> test;    cout << test.g(1, 2);    return 0;}


这时候会报错说,
templat.cpp: In function ‘int main()’:
templat.cpp:21:21: error: no matching function for call to ‘A<int>::g(int, int)’
templat.cpp:21:21: note: candidate is:
templat.cpp:13:3: note: T A<T>::g(T&, T&) [with T = int]
templat.cpp:13:3: note:   no known conversion for argument 1 from ‘int’ to ‘int&’

但是如果在函数g的形参定义改为:
T g(const T &a,const  T &b);
就可以直接传常数的了,我觉得是不是函数引用的问题,引用是一个对象的别名,其就是这个对象只是换了个名字,但如果只传个常数,该变量没有名字,而且引用必须初始化,所以引起了该问题,但为什么加const就可以传常数了?
其实要不然改变了引用值, 原来常量是变还是不变呢,这么一想就转过来了,感觉原因还是引用对一个对象来说不是一个副本了,而就是这个对象,如果直接改变的话,常数值是不能改变的,所以const限定下引用值不变就OK了。所以还是得有&的概念才好

0 0
原创粉丝点击