简单的运算符重载=无法正常工作

cal*_*pto 4 c++ compiler-errors operator-overloading

我正在修改我的integer课程(这不是我最新的副本,但它适用-std=c++0x).我遇到了一个问题:无论我做什么,简单的操作符重载都会拒绝工作.这段代码:

#include <deque>
#include <iostream>
#include <stdint.h>

class integer{
    private:
        std::deque <uint8_t> value;

    public:
        integer(){}

        integer operator=(int rhs){
            return *this;
        }
};

int main() {
        integer a = 132;        
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

给了我:error: conversion from ‘int’ to non-scalar type ‘integer’ requested,但这不是重载的全部意义operator=吗?我已将int部分更改为template <typename T>但不起作用.

我错过了什么?

Lig*_*ica 6

不,你根本没有使用=操作员; 即使=存在符号,也只能使用构造函数进行初始化.出于这个原因,有些人更喜欢建筑类型的初始化:

T a = 1;    // ctor
T b(2);     // ctor
T c; c = 3; // ctor then op=
Run Code Online (Sandbox Code Playgroud)

所以,你需要一个可以采用的构造函数int.别忘记标记它explicit.

另外,顺便说一句,赋值运算符应返回引用.