2017-02-13 18 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(); 
} 

錯誤:克++ 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; 
} 

此外,在int類型的返回值const沒有做太多,因爲它可以被複制到一個非恆定int。然而,返回一個參考是另一個問題。

+0

非常感謝。已經在這個「東西」2小時 –

相關問題