我想创建一个const对象的临时副本,并以非const方式使用它:
struct S {
S& f() { return *this; }
};
int main() {
const S a{};
S{a}.f(); // Error on this line
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用msvc(Visual Studio 2017,C++ 14),我收到此错误:
错误C2662'S&S :: f(void)':无法将'this'指针从'const S'转换为'S&'
如果我将大括号初始化更改为经典初始化,它可以工作:
S{a}.f(); // Does not work
S(a).f(); // Works
Run Code Online (Sandbox Code Playgroud)
两种变体在gcc中编译都很好.我错过了什么或这是一个编译器错误?
在msvc中编译以下示例时,我得到了
'Interface'无法访问,因为'Base'使用'private'继承'Interface'
在标有的行中Error.当调用foo使用相同类型的类型别名限定时,它可以工作.我用msvc和ideone测试过.
为什么这两个电话不相等?
struct Interface {};
template<class T>
struct Base : private T
{
void foo() {}
};
using BaseX = Base<Interface>;
class Derived : Base<Interface>
{
Derived() {
Base<Interface>::foo(); // Error
BaseX::foo(); // Works
}
};
Run Code Online (Sandbox Code Playgroud)