尝试调用转换构造函数的编译器错误

时间:2017-02-13 17:49:14

标签: c++

以下代码不起作用。我不知道为什么。这与隐式/显式有关吗?这叫做转换吗?

#include <type_traits>

template<typename T>
class A { 
public:

    A(T x) {_x=x;}
    template<typename T2> explicit A(const A<T2> &r) {}
    template<typename T2> explicit A(A<T2> &r){}
    template<typename T2> 
    void operator=(const A<T2>& rhs) { _x = rhs._x; }
    template<typename T2> 
    void operator=(A<T2>& rhs) { _x = rhs._x; }
    T _x; 
};

int main() {
        const A<int> a(10);
        A<int> b = a;
        b = A<int>(5);
        A<int> c(a);
        b(a); // not working. why?
}

错误:g ++ 6

test.cpp: In function ‘int main()’:
test.cpp:25:12: error: no match for call to ‘(A<int>) (const A<int>&)’
         b(a); // not working. why?

1 个答案:

答案 0 :(得分:2)

我不确定你期望b(a);做什么,但它不会做你想要的。一个对象只能构造一次。构建完成后,您无法重建它。当你b(a);时,你所拥有的是你试着打电话给班级的operator()。由于您没有,因此会出现编译错误。如果您想将b设置为a的值,那么您需要

b = a;