Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 运算符的简单重载=不工作_C++_Compiler Errors_Operator Overloading - Fatal编程技术网

C++ 运算符的简单重载=不工作

C++ 运算符的简单重载=不工作,c++,compiler-errors,operator-overloading,C++,Compiler Errors,Operator Overloading,我正在修改我的类(这不是我最新的副本,但它可以与-std=c++0x一起使用)。我遇到了一个小问题:一个简单的操作符重载不管我做什么都拒绝工作。此代码: #include <deque> #include <iostream> #include <stdint.h> class integer{ private: std::deque <uint8_t> value; public: intege

我正在修改我的类(这不是我最新的副本,但它可以与
-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;
}
#包括
#包括
#包括
类整数{
私人:
std::deque值;
公众:
整数(){}
整数运算符=(int rhs){
归还*这个;
}
};
int main(){
整数a=132;
返回0;
}
告诉我:
错误:请求将“int”转换为非标量类型的“integer”
,但这不是重载
运算符=
的全部要点吗?我已将
int
部分更改为
template
,但这也不起作用

我错过了什么

integer a = 132; 
是初始化。它调用转换构造函数,而不是
运算符=

integer a;
a = 132; 
应该可以工作,但更好地定义构造函数:

integer(int rhs){}

还要注意,
操作符=
应该通过引用返回。

否。您根本没有使用
=
操作符;即使存在
=
符号,也只能使用构造函数进行初始化。出于这个原因,有些人更喜欢结构类型初始化:

T a = 1;    // ctor
T b(2);     // ctor
T c; c = 3; // ctor then op=
因此,您需要一个可以接受
int
的构造函数。不要忘记将其标记为显式


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

此外,赋值运算符不应该按值返回。您的帖子中缺少大写字母。如果您试图将int转换为整数(我假设您正在执行此操作),您可能希望实现一个复制构造函数,该构造函数采用int而不是赋值运算符。