【问题标题】:Why is the const version of a member function always selected even the non-const version exists?为什么即使存在非常量版本,成员函数的 const 版本也总是被选中?
【发布时间】:2014-06-26 17:16:17
【问题描述】:

更新:这是一个错误的问题。没有非常量版本的 string::data();忽略这个问题。对不起!

string::data 有一个常量版本和一个非常量版本。在我下面的代码中,str 显然是一个非常量对象,所以str.data() 应该调用非常量版本。但是,VC++ 2013 不这么认为。

#include <string>

using namespace std;

void f1(char* sz)
{}

template<class stringT>
void f2(stringT& str)
{
    f1(str.data());
}

int main()
{
    string s;

    f2(s);
    // error C2664: 'void f1(char *)' : 
    // cannot convert argument 1 from 'const char *' to 'char *'
}

【问题讨论】:

标签: c++ visual-c++ constants overloading member-functions


【解决方案1】:

string::data 有一个 const 版本和一个非常量版本。

不,它没有。 There is only a const version.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多