指向包含向量问题的实例类的指针<int>
pointer to instance class containing vector<int> issue
我有一个这样的类:
class largeInt{
vector<int> myVector;
largeInt operator* (const largeInt &arg);
}
在我的main中,我不能避免使用指针时的复制:
void main(){
//this works but there are multiple copies: I return a copy of the calculated
//largeInt from the multiplication and then i create a new largeInt from that copy.
largeInt testNum = 10;
largeInt *pNum = new HugeInt( testNum*10);
//i think this code avoid one copy but at the end hI points to a largeInt that has
// myVector = 0 (seems to be a new instance = 0 ). With simple ints this works great.
largeInt i = 10;
largeInt *hI;
hI = &(i*10);
}
我想我在矢量设计中缺少/没有管理一些东西。我可以实现指针的无复制赋值,即使没有实例化一个新的largeInt?谢谢各位专家!
hI = &(i*10);
获取一个临时 largeInt的地址,该地址在';'之后立即被销毁,因此hI
指向无效内存。
当你乘两个largeInt
你做得到一个新的实例-这就是乘法的作用。也许你打算做一个operator*=
代替?这应该修改一个现有的实例,而不是创建一个新的。
考虑:
int L = 3, R = 5;
int j = L*R; // You *want* a new instance - L and R shouldn't change
L*=R; // You don't want a new instance - L is modified, R is unchanged
同样,你不应该使用new
在堆上创建largeInt——就像这样做:
largeInt i = 10;
largeInt hi = i*10; // Create a temporary, copy construct from the temporary
或:
largeInt i = 10;
largeInt hi = i; // Copy construction
hi *= 10; // Modify hi directly
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 没有显式声明的int[]中的foreach
- 在c++中访问int到类对象的映射时出错
- 为什么我无法更改"set<set>"循环中的值<int>
- EASTL矢量<向量<int>>连续的
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- 'structstd::对<int,int>'没有名为'push_back'