64,643
社区成员
发帖
与我相关
我的任务
分享
struct S {
void f() const & { std::cout << typeid(this).name() << "-const-lv" << std::endl; }
void f() & { std::cout << typeid(this).name() << "-lv" << std::endl; }
void f() &&{ std::cout << typeid(this).name() << "-rv" << std::endl; }
void f() const &&{ std::cout << typeid(this).name() << "-const-rv" << std::endl; }
};
const S fun()
{
const S s;
return s;
}
int main(){
S s;
s.f(); // prints "lvalue"
std::move(s).f(); // prints "rvalue"
S().f(); // prints "rvalue"
const S cs;
cs.f();
fun().f();
/*
注意这里,注释了这个才能编译过去,之所以编译不过去,是因为这条语句让编译器难以绝定改重载哪个,可能是void f() const &,又可能是void f() const &&。换句话说常右值引用对编译器来说和常左值引用没区别
*/
}
如果注释了fun().f();得到的结果是
P1S-lv
P1S-rv
P1S-rv
PK1S-const-lv
struct A
{
void Do() const
{
std::cout<<"const"<<std::endl;
}
void Do()
{
std::cout<<"noconst"<<std::endl;
}
};
struct B : A
{
};
int main( void )
{
B().Do();
return 0;
}
[/quote]
又看多了几遍,好像看懂了,之前在纠结的是这句:as long as in all other respects the temporary can be converted to the type of the implicit object parameter
我以为all other respects 会包括这种情况: A &r = A(); (显然是不行的),,所以我不知道它的all other respects 是指什么..
struct A
{
void Do() const
{
std::cout<<"const"<<std::endl;
}
void Do()
{
std::cout<<"noconst"<<std::endl;
}
};
struct B : A
{
};
int main( void )
{
B().Do();
return 0;
}