这个或没有可行的重载`=`的const错误

时间:2017-02-13 18:48:16

标签: c++ templates const

我想这是由=运算符的重载引起的。但即使我将代码简化了9次之后,我也不知道为什么。

test9.cpp:

template<typename T>
class A {
public:
    A(const T x): _x(x) {}
    A() : _x(0) {}

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

template <typename T>
class A_wrap {
public:
    A_wrap(const T x) : _a(x) {}
    const A<T> _a;
};

template <typename T>
class X {
public:
    X() {}
    const int test() const {
        const A_wrap<T> a_wrap(10);
        _a = a_wrap._a;
    }
    A<T> _a;
};

int main() {
    // This works.
    A<int> _a;
    const A_wrap<int> a_wrap(10);
    _a = a_wrap._a;
    // Below doesn't compile.
    X<int> x;
    x.test(); 
}

错误:g ++ 6

test9.cpp:39:12:   required from here
test9.cpp:27:12: error: passing ‘const A<int>’ as ‘this’ argument discards qualifiers [-fpermissive]
         _a = a_wrap._a;
         ~~~^~~~~~~~~~~
test9.cpp:2:7: note:   in call to ‘constexpr A<int>& A<int>::operator=(const A<int>&)’
 class A {
       ^

错误clang ++ 3.8.1:

test9.cpp:27:12: error: no viable overloaded '='
        _a = a_wrap._a;
        ~~ ^ ~~~~~~~~~
test9.cpp:39:7: note: in instantiation of member function 'X<int>::test' requested here
    x.test(); 
      ^
test9.cpp:2:7: note: candidate function (the implicit copy assignment operator) not viable: 'this'
      argument has type 'const A<int>', but method is not marked const
class A {
      ^
test9.cpp:8:10: note: candidate function not viable: 'this' argument has type 'const A<int>', but
      method is not marked const
    void operator=(const A<T2> &rhs) {
         ^
1 error generated.

1 个答案:

答案 0 :(得分:1)

test()

X成员函数
const int test() const {
    const A_wrap<T> a_wrap(10);
    _a = a_wrap._a;
}

定义为const,即不改变类的状态。但是,您正在更改成员变量_a的值,因此会出错。您需要删除函数中的最后一个const

const int test() {
    const A_wrap<T> a_wrap(10);
    _a = a_wrap._a;
}

int类型的返回值中的const也没有太大作用,因为它可以复制到非常量int。但是,返回参考是另一回事。