C++,需要帮助理解使用指针的 vector 类中的一些构造函数和函数

标签 c++ pointers vector constructor inline-functions

大家好;

我必须开发一个 C++ 类库,其中包含一组用于科学计算的数值技术。该库应实现 Vector 类(使用指针),并在头文件“Vector.h”中说明一些基本功能。

#ifndef VECTOR_H
#define VECTOR_H

template <class T>
class CVector {
private:
    int nn; //size of array
    T *v;   //pointer to array of data

public:

    //Default constractor
   CVector();

    //zero based array
    CVector(int n);

    //initialize to constant of value a
    CVector(int n, const T &a);

    //initialize to array a
    CVector(int n, const T *a);

    //copy constractor
    CVector(const CVector &rhs);

    //assignment
    CVector & operator=(const CVector &rhs);

    //i'th element
    inline T & operator[](const int i);

    inline const T & operator[](const int i) const;

    inline int size() const;

    //resize (contents not preserved)
    void resize(int newn);

    //resize and assign a constant value
    void assign(int newn, const T &a);

    //deconstractor
    ~CVector();

};

#endif  /* VECTOR_H */

我是C++的初学者,对上面代码中的一些构造函数和函数的理解有些迷茫。

我的问题是:

1-下面的构造函数是什么概念?

    //initialize to array a
    CVector(int n, const T *a);

我的意思是如何将 vector 初始化为数组a?

2- 复制构造函数和赋值构造函数有什么区别?

    //copy constractor
    CVector(const CVector &rhs);

    //assignment
    CVector & operator=(const CVector &rhs);

3-我知道这个函数是返回 vector 的第i个元素:

    //i'th element
    inline T & operator[](const int i);

但是它和这个有什么区别:

    inline const T & operator[](const int i) const;

我需要理解这个概念,以便知道如何在 .cpp 文件中实现它们以及如何在我的 main 中调用它们。如果你能帮助我,我会很高兴。

最好的问候;

最佳答案

Q1:该构造函数可用于将数组中从 a 开始的 n 个元素的内容填充到 vector 中。

例如:

   float a[42] = { 31, 41, 59 };
   CVector<float> v( 3, a );

Q2:第一个是拷贝构造函数,第二个是赋值运算符。复制构造函数用于将值复制到函数参数、从函数返回值或初始化变量。

例如,复制构造函数用于这些:

CVector<float> foo( CVector<float> v ) { ... }

...
CVector<float> v1;
CVector<float> v2 = foo( v1 ); // Copy constructor used to pass in v1, and to return v2
CVector<float> v3 = v1; // Copy constructor used to copy v1 to v2.

赋值用于此:

CVector<float> v4;
v4 = v1;

Q3。第一个可以用在赋值的左侧。应用于 const 对象时使用 const 版本。

void bar( const float & fval ) { ... }
...
CVector<float> v1( 3, a );
v1[0] = 42;   // Non-const operator[]

const CVector<float> v2 = v1; 
float value = v2[0];  // Const operator[]
bar( v2[0] ); // Const operator[]

关于C++,需要帮助理解使用指针的 vector 类中的一些构造函数和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5833226/

相关文章:

c - 尝试从列表中删除节点时出现段错误?

c++ - 我的范围循环出现逻辑错误

python - 如何在 sympy.physics.vector 模块中定义左手坐标系?

c++ - 在 C++/CLI 中创建某种 C++ 对象列表

c++ - 为什么 std::algorithms 不能直接在容器上工作?

c++ - 近似 e^1 :( 的错误逻辑

c++ - 如何将 istream * 转换为字符串或仅打印它?

C++继承,从基类调用派生函数

c++ - 填充指针数组,退出时删除

c++ - 调试断言失败,C++ vector 下标超出范围