C ++ - 无法重载赋值运算符

时间:2016-10-29 14:57:18

标签: c++ visual-c++ operator-overloading overloading

我正在尝试重载赋值运算符但它似乎不起作用。 The code is based on this answer。我已经搜索了重载赋值运算符的其他示例,但似乎我的代码不应该运行。

这是我的代码:

#pragma once

#include <assert.h>

class ReadOnlyInt
{
public: 
    ReadOnlyInt(): assigned(false) {}

    ReadOnlyInt& operator=(int v);
    operator int() const ;
private: 
    int value; 
    bool assigned; 
}; 

ReadOnlyInt& ReadOnlyInt::operator=(int v)
{
    assert(!assigned); 
    value = v; 
    assigned = true; 
    return *this; 
}   

ReadOnlyInt::operator int() const 
{ 
    assert(assigned); 
    return value; 
}

智能感知不会发出任何警告,但operator=不会突出显示为关键字。

现在,如果我做出一个分配,Intellisense确实认识到它是不可能的:

ReadOnlyInt bar = 12;
  

没有合适的构造函数可以从“int”转换为“ReadOnlyInt”

但这有效:

int foo = bar;

解决方案

这个问题被标记为重复,所以我无法回答。这是我根据这个问题的评论和答案提出的解决方案:

ReadOnlyInt::ReadOnlyInt()
: assigned(false)
{}

ReadOnlyInt::ReadOnlyInt(int v)
: value(v), assigned(true)
{}

1 个答案:

答案 0 :(得分:1)

您无法同时初始化和声明。你需要这样做

ReadOnlyInt bar;
bar = 12;

这是因为ReadOnlyInt没有适当的构造函数来获取int参数。