c++ - 从 'int' 到非标量类型赋值运算符的转换 - object 到 int

标签 c++ type-conversion overloading operator-keyword implicit-conversion

我在将 int 分配给对象时遇到问题,如下所示:

int main() {
     Wurzel a;  
     Wurzel b=3; // error: conversion from 'int' to non-scalar type 'Wurzel' requested

     return 0;
}

我的带有赋值运算符的类:

class Wurzel{
private:
    int wurzelexponent;
    int wert;

public:

    Wurzel(){
        wurzelexponent=1;
        wert=1;
    }

    Wurzel& operator =(const Wurzel &w)  {

        wurzelexponent = w.wurzelexponent;

    }
};

我必须使用 = 运算符来执行此操作

问题出在哪里?

最佳答案

I must do this with = operator

不,你不能。因为 Wurzel b=3; 不是赋值,而是初始化,copy initialization 。正如错误消息所述,您需要 converting constructor来完成它。

class Wurzel{
    ...
public:
    ...
    Wurzel(int x) : wurzelexponent(x), wert(1) {}
    Wurzel(int x, int y) : wurzelexponent(x), wert(y) {}
    ...
};

然后

Wurzel b = 3;      // Wurzel::Wurzel(int) will be called
Wurzel b = {3, 2}; // Wurzel::Wurzel(int, int) will be called [1]

注意,operator=仅用于赋值,如:

Wurzel b;      // default initialized
b = something; // this is assignment, operator=() will be used

[1]从C++11引入了具有多个参数的转换构造函数。

关于c++ - 从 'int' 到非标量类型赋值运算符的转换 - object 到 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38543308/

相关文章:

c++ - 使用 set_union 和 set_intersection 时出错

ios - NSParagraphStyle 属性名称 : Conversion from swift 3 to swift 4. 2

c# - 具有 "params"关键字的方法的多个重载

c++ - 玩家移动时,GameBoy Advance对象未显示在正确的位置

C++函数指针问题

c - 使用格式说明符进行转换

c++ - SQL numeric(18,0) 数据类型对应的 C++ 数据类型是什么?

c# - 根据参数值重载方法?

vhdl - ModelSim 不编译重载函数和未定义范围类型

c++ - CGAL继承