相关疑难解决方法(0)

在nonconst对象上,为什么C++不会使用public-const和private-nonconst重载调用方法的const版本?

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对象上调用该方法?

c++ const private public

26
推荐指数
2
解决办法
742
查看次数

一个templatised构造函数可以代表一个已删除的复制构造函数吗?

考虑

template<typename T>
struct Foo
{
    Foo(const Foo&) = delete;
    template <typename Y>
    Foo(const Foo<Y>&){}
};
Run Code Online (Sandbox Code Playgroud)

模板构造函数的适当实例化是否代表复制构造函数?我知道它通常不会(因为复制构造函数不能是模板函数)但在这里我删除了复制构造函数.

c++

7
推荐指数
1
解决办法
133
查看次数

编译器提供私有构造函数作为程序代码中的候选者

#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 …

c++ gcc constructor clang

3
推荐指数
1
解决办法
87
查看次数

标签 统计

c++ ×3

clang ×1

const ×1

constructor ×1

gcc ×1

private ×1

public ×1