[英]How to assign a pointer to object to another pointer to object of same class?
I have a class called arr
and it has a function named _union
written like this:我有一个名为arr
的 class ,它有一个名为_union
的 function ,如下所示:
template<class T>
arr<T> *arr<T>::_union(arr<T> B) {
arr<T> *C(this->length + B._length());
bool isPresent = false;
for (int i = 0; i < length; i++)
C->push_back(this->get(i));
for (int j = 0; j < B._length(); j++) {
for (int k = 0; k < C->_length(); k++) {
if (B.get(j) == C->get(k))
isPresent = true;
}
if (!isPresent)
C->push_back(B.get(j));
isPresent = false;
}
return C;
}
The function returns a pointer of an object that was newly created inside this function's scope. function 返回 object 的指针,该指针是在此函数的 scope 中新创建的。
In main function, I wrote code like this:在主要的 function 中,我编写了如下代码:
arr<int> *a3 = a1._union(a2);
a3->display();
When I run, this gives me an error:当我运行时,这给了我一个错误:
What is the problem here?这里有什么问题? If I don't use any pointers and just return normal object then everything is fine.如果我不使用任何指针而只返回正常的 object 那么一切都很好。
Please help me.请帮我。 Also I don't have any copy constructers inside the class.此外,我在 class 中没有任何复制构造函数。 I am just trying to create my own array class with data and functions.我只是想用数据和函数创建我自己的数组 class 。
In this code在这段代码中
arr<T> *C(this->length + B._length());
C
is a pointer and this->length + B._length()
is an integer, hence the error. C
是一个指针, this->length + B._length()
是一个 integer,因此出现错误。 You can't assign an integer to a pointer.您不能将 integer 分配给指针。
I guess you were trying to write this code我猜你是想写这段代码
arr<T> *C = new arr<T>(this->length + B._length());
This code allocates a new arr<T>
object using new
and calls the a constructor for that object using the integer parameter this->length + B._length()
.此代码使用new
分配一个新的arr<T>
object 并使用 integer 参数this->length + B._length()
调用该 object 的构造函数。
However is usually a bad idea to use dynamic allocation like this.然而,像这样使用动态分配通常是个坏主意。 You should think about redesigning your function without using pointers.您应该考虑在不使用指针的情况下重新设计您的 function。
template<class T>
arr<T> arr<T>::_union(arr<T> B) {
arr<T> C(this->length + B._length());
...
return C;
}
This will require you to define a copy constructor etc for arr<T>
.这将要求您为arr<T>
定义一个复制构造函数等。 But that is normal C++ programming you shouldn't be reluctant to do it.但这是正常的 C++ 编程,你不应该不愿意这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.