使用重载'*'运算符创建多个副本
Creating multiple copies using overloaded '*' operator
我想做的是使用乘法运算符来创建一个对象的多个副本实例。
。
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。为什么乘法运算符不能接受多个参数,除非它是一个朋友函数(我在网上搜索过,但对它知之甚少)?
谢谢
- 这是对操作符的滥用,直接使用复制构造函数。
-
instance * 5
与5 * 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;
}
相关文章:
- 在为LINUX创建共享库时,如何避免STL的私有/弱副本
- 创建提升::shared_ptr的深层副本
- Eigen - matrix.transpose 会创建矩阵的副本吗?
- 将 MatrixXd 的行传递给要修改的函数,而不在 Eigen 中创建副本
- 创建字符串流副本
- 是否可以在并行区域中为共享 2D 数组创建选定元素的线程本地副本?(共享,私有,障碍:OPenMP)
- C++ 在其自己的类中创建对象的修改副本
- std::可选参数会创建副本吗?
- 使用 lambda 表达式创建线程时,如何为每个线程提供自己的 lambda 表达式副本
- C++ 如何创建链表的副本作为类对象
- MSVC 2017 在共享库中创建模板函数的副本
- 我如何创建一个双重指针的深层副本,涉及其他类(C )
- 是 std::make_pair 在将对象添加到地图时创建副本
- 阻止用户创建班级对象的副本,但允许动态的对象有什么好处
- 取消引用指针以创建数组的副本
- 创建std :: vector减去一个元素的副本的最快方法
- 此分配是否创建副本
- C++ Qt如何通过小的更改创建GUI的副本
- C++ STL:在创建 std::string 的 const 副本时将更改 c_str()
- 使用矢量push_back代码创建对象副本时遇到问题