无法将参数从'int'转换为'int&' [英] Cannot convert parameter from 'int' to 'int&'

查看:1369
本文介绍了无法将参数从'int'转换为'int&'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循的是pluralsight C ++课程,其中包含以下代码:

I'm following the pluralsight C++ course, and in it is the following code:

#include <iostream>

template <class T>
T max(T& t1, T& t2)
{
    return t1 < t2 ? t2 : t1;
}

int main()
{
    std::cout << "Max of 33 and 44 is " << max(33, 44) << std::endl;

    return 0;
}

我输入了这段代码,我得到一个错误消息:

I typed over this piece of code, but unlike the code of the course, I get an error message:

C2664: 'max' : cannot convert parameter 1 from 'int' to 'int &'

课程中的代码是在Visual Studio Express 2010中编写的,而我的是在Visual Studio Ultimate 2010。

The code in the course is written in Visual Studio Express 2010, while mine is written in Visual Studio Ultimate 2010.

EDIT

感谢大家

推荐答案

因为文字(和一般的右值) const引用(因为如果被调用者可以改变它们将没有意义)。可以通过值或const引用:

Because literals (and rvalues in general) cannot be passed by non-const reference (since it would make no sense if the callee could change them). Either pass by value or by const reference:

template <class T>
T max(const T& t1, const T& t2)
{
    return t1 < t2 ? t2 : t1;
}

template <class T>
T max(T t1, T t2)
{
    return t1 < t2 ? t2 : t1;
}

这篇关于无法将参数从'int'转换为'int&amp;'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆