我想做的是,允许使用 setter 函数传递指针、引用或常量引用:
class A{
std::string * p;
std::string st;
public:
A():p(0)
{}
A& setS(const std::string& s){
std::cout<<"called with const std::string&\n";
st = s;
p = &st;
return *this;
}
A& setS(std::string& s) {
std::cout<<"called with std::string&\n";
p = &s;
return *this;
}
A& setS(std::string* s) {
std::cout<<"called with std::string*\n";
p = s;
return *this;
}
};
int main(){
std::string s;
A a;
a.setS(std::move(s)) //const std::string&
.setS("") //const std::string&
.setS(s) //std::string&
.setS(0); //std::string*
//if std::string* version is not defined,
//setS(0) calls the const std::string& version and throws exception
return 0;
}
但是我已经看到,如果指针版本不存在,则setS(0)
调用函数的const std::string&
版本。setS()
指针和参考版本之间或其他任何重要的版本之间是否存在歧义?它是否定义明确并期望在所有编译器中以相同的方式工作?