2017-02-13 1 views
0

Я предполагаю, что это вызвано моими перегрузками оператора =. Но я не знаю, почему, даже после того, как я упростил код в 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 { 
    ^

Ошибка лязг ++ 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

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; 
} 

Также const в возвращаемом значении типа Int не делать, поскольку это может быть скопировано на непостоянную int. Однако возвращение ссылки - это другое дело.

+0

большое спасибо. были на этой «вещи» за 2 часа –

Смежные вопросы