在构造函数中使用对象
Using object inside constructor
我正在创建继承STL的自己的向量类。我在创建对象时遇到了一个问题。
这是我的班。
using namespace std;
template <class T>
class ArithmeticVector : public vector<T>{
public:
vector<T> vector; //maybe I should not initalize this
ArithmeticVector(){};
ArithmeticVector(T n) : vector(n){
//something here
};
在主要;
ArithmeticVector<double> v9(5);
或
ArithmeticVector<int> v1(3);
我想要的是创建v9
矢量或v1
矢量就像STL矢量类型。但我得到的是新创建对象中的一个向量。首先,我想让我的对象是一个向量。
也许我应该在构造函数中使用v1
对象?谢谢你的帮助。
如果您需要在std::vector
上进行元素操作和数学运算,请使用std::valarray
。如果没有,我不明白你为什么要子类化std::vector
。
不要继承std::
容器,它们没有虚析构函数,如果从指向基的指针中删除,会在你脸上爆炸。
EDIT如果需要在std::vector
上定义操作,可以在类外定义操作符,并使用其公共接口。
首先,您发布的代码无法编译,因为这一行:
public:
vector<T> vector; //maybe i should not initalize this
你应该看到这个错误:
declaration of ‘std::vector<T, std::allocator<_Tp1> > ArithmeticVector<T>::vector’
/usr/include/c++/4.4/bits/stl_vector.h:171: error: changes meaning of ‘vector’ from ‘class std::vector<T, std::allocator<_Tp1> >’
,因为你在类模板声明之上引入了整个STD命名空间,使得名称"vector"可见,然后你用它来声明一个对象。这就像写"double double;"。
我想要的是创建v9矢量或v1矢量就像STL矢量类型。
如果这是你想要的,下面是完成它的代码:
#include <vector>
#include <memory>
template
<
class Type
>
class ArithmeticVector
:
public std::vector<Type, std::allocator<Type> >
{
public:
ArithmeticVector()
:
std::vector<Type>()
{}
// Your constructor takes Type for an argument here, which is wrong:
// any type T that is not convertible to std::vector<Type>::size_type
// will fail at this point in your code; ArithmeticVector (T n)
ArithmeticVector(typename std::vector<Type>::size_type t)
:
std::vector<Type>(t)
{}
template<typename Iterator>
ArithmeticVector(Iterator begin, Iterator end)
:
std::vector<Type>(begin, end)
{}
};
int main(int argc, const char *argv[])
{
ArithmeticVector<double> aVec (3);
return 0;
}
如果你对与STL中定义的算法(累加等)不同的向量的算术运算感兴趣,而不是专注于向量类和添加成员函数,你可以考虑为期望特定向量概念的向量编写泛型算法。这样你就完全不用考虑继承问题了,你的泛型算法可以在不同的vector概念上工作。
相关文章:
- 类中的 Arduino 对象构造函数设置垃圾值
- 编译错误:临时对象构造函数中缺少参数
- 双指针在使用 new 时不调用对象构造函数
- 以支持继承的方式将自身shared_ptr添加到对象构造函数中的向量中
- 在创建对象向量时,不为每个对象唯一调用默认对象构造函数
- GCC __attribute__((constructor)) 在对象构造函数之前调用
- 自定义对象构造函数在循环外部循环
- 从全局对象构造函数停止监视器计时器
- Arduino 上的 Sketch 停止在对象构造函数中执行
- 通过在引用线程对象来传递取消引用的“this”指针来在函数对象构造函数中创建线程是好是坏
- 为什么当对象构造函数投入新表达式时,为什么不调用DealLocation函数
- 临时结构对象构造函数奇数调用
- 未显式引用对象的全局对象构造函数在最终二进制文件 - LD 中被丢弃
- 为什么 Clang++ 不在另一个静态库中运行全局对象构造函数?
- 在未加载上下文的情况下在对象构造函数中使用OpenGL函数
- 为什么我们需要一个用户提供的const对象构造函数
- 对象构造函数的C++数组
- 将子结构值设置为对象构造函数中安全的纯虚拟函数返回的值
- C等价于新对象(构造函数)
- C++:直接在参数列表中使用数组文字的对象构造函数