class C
{
public:
void foo() const {}
private:
void foo() {}
};
int main()
{
C c;
c.foo();
}
Run Code Online (Sandbox Code Playgroud)
MSVC 2013不喜欢这样:
> error C2248: 'C::foo' : cannot access private member declared in class 'C'
Run Code Online (Sandbox Code Playgroud)
如果我转向const参考,它的工作原理:
const_cast<C const &>(c).foo();
Run Code Online (Sandbox Code Playgroud)
为什么我不能const在非const对象上调用该方法?
考虑
template<typename T>
struct Foo
{
Foo(const Foo&) = delete;
template <typename Y>
Foo(const Foo<Y>&){}
};
Run Code Online (Sandbox Code Playgroud)
模板构造函数的适当实例化是否代表复制构造函数?我知道它通常不会(因为复制构造函数不能是模板函数)但在这里我删除了复制构造函数.
#include <iostream>
using namespace std;
class Test{
private:
Test(int a, int b=0)
{
cout << "private constructor\n";
}
public:
Test(int a)
{
cout << "public constructor\n";
}
};
int main()
{
Test t(1);
}
Run Code Online (Sandbox Code Playgroud)
当我试图编译代码时gcc说:
test.cpp: In function ‘int main()’:
test.cpp:20:10: error: call of overloaded ‘Test(int)’ is ambiguous
Test t(1);
^
test.cpp:12:2: note: candidate: Test::Test(int)
Test(int a)
^
test.cpp:7:2: note: candidate: Test::Test(int, int)
Test(int a, int b=0)
^
test.cpp:5:7: note: candidate: Test::Test(const Test&)
class Test{
^
Run Code Online (Sandbox Code Playgroud)
并clang …