这个问题在这里已经有了答案:Callingaconstfunctionratherthanitsnon-constversion(4个回答)关闭4年前。例如,假设我有一个类(class):classFoo{public:std::string&Name(){m_maybe_modified=true;returnm_name;}conststd::string&Name()const{returnm_name;}protected:std::stringm_name;boolm_maybe_modified;};在代码的其他地方,我有这样的东西:Foo*a;//Dostuff...st
这个问题在这里已经有了答案:Callingaconstfunctionratherthanitsnon-constversion(4个回答)关闭4年前。例如,假设我有一个类(class):classFoo{public:std::string&Name(){m_maybe_modified=true;returnm_name;}conststd::string&Name()const{returnm_name;}protected:std::stringm_name;boolm_maybe_modified;};在代码的其他地方,我有这样的东西:Foo*a;//Dostuff...st
stringaux;intmaxy,auxx=0;cin>>aux;maxy=(int)sqrt(aux.size());我得到:1>errorC2668:'sqrt':ambiguouscalltooverloadedfunction1>couldbe'longdoublesqrt(longdouble)'1>or'floatsqrt(float)'1>or'doublesqrt(double)'为什么? 最佳答案 string::size()返回size_t,而sqrt在其任何版本中都不接受它。所以编译器必须强制转换,并且不能选
stringaux;intmaxy,auxx=0;cin>>aux;maxy=(int)sqrt(aux.size());我得到:1>errorC2668:'sqrt':ambiguouscalltooverloadedfunction1>couldbe'longdoublesqrt(longdouble)'1>or'floatsqrt(float)'1>or'doublesqrt(double)'为什么? 最佳答案 string::size()返回size_t,而sqrt在其任何版本中都不接受它。所以编译器必须强制转换,并且不能选
#includestructA{};structB:publicA{};templatevoidfoo(constT&x){std::cout打印出来:CalledACalledtemplate我的印象是总是会选择合适的非模板函数而不是模板函数。有人可以向我解释导致这个有点令人惊讶的结果的解决步骤吗? 最佳答案 Iwasundertheimpressionthatasuitablenon-templatefunctionwouldalwaysbechosenoveratemplatefunction.这仅在模板和非模板是同样好的候选
#includestructA{};structB:publicA{};templatevoidfoo(constT&x){std::cout打印出来:CalledACalledtemplate我的印象是总是会选择合适的非模板函数而不是模板函数。有人可以向我解释导致这个有点令人惊讶的结果的解决步骤吗? 最佳答案 Iwasundertheimpressionthatasuitablenon-templatefunctionwouldalwaysbechosenoveratemplatefunction.这仅在模板和非模板是同样好的候选
#includetemplatevoidfoo(U&,T&){std::coutvoidfoo(int&,constT&){std::cout调用第二个foo重载,编译器只需要执行一次模板类型推导,但对于第一次重载,它需要执行两次。你能解释一下为什么调用第一个重载吗? 最佳答案 重载解决方案分多个步骤完成。首先,通过名称查找,我们选择可行的候选人列表。在这种情况下,即:templatevoidfoo(U&,T&);//withU=int,T=doubletemplatevoidfoo(int&,constT&)//withT=dou
#includetemplatevoidfoo(U&,T&){std::coutvoidfoo(int&,constT&){std::cout调用第二个foo重载,编译器只需要执行一次模板类型推导,但对于第一次重载,它需要执行两次。你能解释一下为什么调用第一个重载吗? 最佳答案 重载解决方案分多个步骤完成。首先,通过名称查找,我们选择可行的候选人列表。在这种情况下,即:templatevoidfoo(U&,T&);//withU=int,T=doubletemplatevoidfoo(int&,constT&)//withT=dou
clang和gcc在以下代码的行为上有所不同:structfoo{foo(int);};structwaldo{templateoperatorT();};intmain(){waldow;foof{w};}clang接受此代码,并调用foo(int)构造函数。但是,gcc提示foo(int)构造函数与隐式生成的复制和移动构造函数之间存在歧义:test.cpp:Infunction'intmain()':test.cpp:15:12:error:callofoverloaded'foo()'isambiguousfoof{w};^test.cpp:15:12:note:candidat
clang和gcc在以下代码的行为上有所不同:structfoo{foo(int);};structwaldo{templateoperatorT();};intmain(){waldow;foof{w};}clang接受此代码,并调用foo(int)构造函数。但是,gcc提示foo(int)构造函数与隐式生成的复制和移动构造函数之间存在歧义:test.cpp:Infunction'intmain()':test.cpp:15:12:error:callofoverloaded'foo()'isambiguousfoof{w};^test.cpp:15:12:note:candidat