【问题标题】:C++ - Unable to overload assignment operator [duplicate]C ++ - 无法重载赋值运算符[重复]
【发布时间】:2016-10-29 14:57:18
【问题描述】:

我试图重载赋值运算符,但它似乎不起作用。 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; 
}

Intellisense 不发出任何警告,但 operator= 未突出显示为关键字。

现在,如果我进行分配,Intellisense 确实认识到这是不可能的:

ReadOnlyInt bar = 12;

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

但是这可行:

int foo = bar;

解决方案

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

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

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

【问题讨论】:

  • 如果你做ReadOnlyInt bar然后分配bar = 12;是否有效
  • ReadOnlyInt bar = 12; 不做作业;这是复制初始化。要使用分配,请创建对象并单独分配给它:ReadOnlyInt bar; bar = 12;.

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


【解决方案1】:

你不能同时初始化和声明。你需要这样做

ReadOnlyInt bar;
bar = 12;

这是因为没有合适的 ReadOnlyInt 构造函数接受 int 参数。

【讨论】:

    猜你喜欢
    • 2013-03-30
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 2018-12-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    相关资源
    最近更新 更多