[英]Custom Vector class, return vector like an array in c++
I'm trying to create a custom vector class and overloading all operators.我正在尝试创建一个自定义向量 class 并重载所有运算符。 consider the following code:考虑以下代码:
template <class T>
class vector{
private:
T * arrayOfObj;
// other class members
public:
Vector(){
arrayOfObj = new T[100];
}
vector(int size);
// other functions for vector class, overloaded [], =, etc.
}
in another class, I need to return the vector but with a pointer like when we return an array:在另一个 class 中,我需要返回向量但使用指针,就像我们返回数组时一样:
#include "B.h"
class c {
vector<B> vect;
public:
B * getArray(){
return vect;
}
First, is it possible to retrun a vector like an array?首先,是否可以像数组一样重新运行向量? Also, if I wanted to access the dynamic array encapsulated inside the vector class without using a public function to return the array, how should be my approach?另外,如果我想访问封装在向量 class 内的动态数组而不使用公共 function 返回数组,我的方法应该如何?
First, is it possible to retrun a vector like an array?首先,是否可以像数组一样重新运行向量?
Sure, that's what std::vector::data()
does.当然,这就是std::vector::data()
所做的。 It's as simple as doing return arrayOfObj;
就像做return arrayOfObj;
in whatever method or operator overload.在任何方法或运算符重载中。
Also, if I wanted to access the dynamic array encapsulated inside the vector class without using a public function to return the array, how should be my approach?另外,如果我想访问封装在向量 class 内的动态数组而不使用公共 function 返回数组,我的方法应该如何?
Not possible.不可能。 Either you allow access to your internal storage via a public function or you don't allow that, your choice.要么您允许通过公共 function 访问您的内部存储,要么您不允许这样做,您的选择。 In c::getArray()
you could also copy all elements of vect
into a new array - this way noone will alter vect
from the outside and you don't have to provide access to internal storage of vector
class.在c::getArray()
中,您还可以将vect
的所有元素复制到一个新数组中 - 这样没有人会从外部更改vect
并且您不必提供对vector
class 内部存储的访问。
There is also friend
mechanism that allows one function or class to access private members of another class, but it's usually worse than public access .还有一种friend
元机制允许一个 function 或 class 访问另一个 class 的私有成员,但通常比公共访问更糟糕。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.