使用重载'*'运算符创建多个副本

Creating multiple copies using overloaded '*' operator

本文关键字:副本 创建 运算符 重载      更新时间:2023-10-16

我想做的是使用乘法运算符来创建一个对象的多个副本实例。

myclass instance;
instance * 5;

将创建5个实例副本。所以我使用一个对象数组来创建这些实例。

cube* operator* (int i, const cube& thing) {
        cube* objectarr = new cube[i];
        for (int j = 0; j < i; j++) {
            objectarr[i] = thing;
        }
        std::cout << i << " number of copies createdn";
        return objectarr;
    }

但是我得到一个错误说"这个函数的参数太多"。然而,如果我把它设为友元函数,那么它就可以有多个参数。当我尝试执行一个示例时,问题出现了。

#include <iostream>
#define TB 't'
struct cube {
    int height;
    int width;
    int bredth;
    cube() {
        height = 0;
        width = 0;
        bredth = 0;
    }
    cube(int i, int j, int k) {
        height = i;
        width = j;
        bredth = k;
    }
    cube operator+=(const cube& c);
    friend cube* operator* (int i, const cube& thing) {
        cube* objectarr = new cube[i];
        for (int j = 0; j < i; j++) {
            objectarr[i] = thing;
        }
        std::cout << i << " number of copies createdn";
        return objectarr;
    }
};
int main() {
    cube c1(10, 20, 30);
    cube* mptr = new cube;
    mptr = 4 * c1;
    for (int i = 0; i < 4; i++) {
        std::cout << mptr[i].height << TB << mptr[i].width << TB << mptr[i].bredth << std::endl;
    }
    return 0;
}

以上代码的输出如下:

4 number of copies created
0       0       0
0       0       0
0       0       0
0       0       0

I want to know

1。为什么会发生这种情况?

2。为什么乘法运算符不能接受多个参数,除非它是一个朋友函数(我在网上搜索过,但对它知之甚少)?

谢谢

    这是对操作符的滥用,直接使用复制构造函数。
  1. instance * 55 * instance不相同。你得到了后者。

恐怕不行。

在重载操作符时,不允许更改操作符的。这意味着你不能调整参数的数量。

您所引用的friend函数将与您的特定类在"类外"作用域的重载乘法运算符的版本相关:因此它接受2个参数。

您更愿意使用设计模式的工厂来创建您的类的多个实例。

如果重载是成员,则*this是操作符的左侧,并且只有一个显式形参。
如果你想让左边的实参不是你的类,你必须让重载成为一个自由函数。

例如,如果您有

struct A
{
     int operator *(int x) { return x * y; } 
     int y;
};
int operator*(int x, A a) { return a.y * x }

A a{2};
然后

int z = a * 2; 

调用a.operator*(2),而

int w = 2 * a;

调用operator*(2, a)

您的特定运算符的更好实现是

std::vector<cube> operator* (int i, const cube& thing) 
{
    return std::vector<cube>(i, thing);
}

或者如果你想要对称:

struct cube
{
   // ...
   std::vector<cube> operator*(int i) const { return std::vector<cube>(i, *this); }
};
std::vector<cube> operator* (int i, const cube& thing) 
{
    return thing * i;
}