c++ - 此或无可行重载的 Const 错误 `=`

标签 c++ templates constants

我想这是由于我重载了 = 运算符造成的。但是我不知道为什么,我简化了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.

最佳答案

Xtest()成员函数

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。不过,返回引用是另一回事。

关于c++ - 此或无可行重载的 Const 错误 `=`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42211329/

相关文章:

c++ - 从字符串到 Ice::ByteSeq 的转换

c++ - 如何在opengl中以给定的起点绘制弧线?

c++ - 通过在 C++ 中单独直接访问其迭代器来删除容器的元素

c++ - 在编译时引用 const 值——什么时候 const 的定义才真正可用?

c++ - 在 Bison 和 Flex 中使用变体

javascript - 是否可以在 Coldfusion 服务器端将 HTML 标记编译为可模板化的 javascript?

c++ - 函数模板的显式实例化何时发生实例化

c++ - 函数模板和通用函数是正确的术语吗?

c++ - 在类头中声明并初始化 const 结构

Go 的 const 命名约定