向量不取我给出的值
Vector doesnt take the value I give
本文关键字:向量 更新时间:2023-10-16
感谢您的帮助!问题是,当我运行程序并给出向量的维度时,它需要另一个大整数或负值。正如你所看到的,我使用模板,这是第一次,所以也许这就是问题所在。这是代码,谢谢!
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <new>
using namespace std;
template <class Tipo>
class Vector
{
friend ostream& operator<<(ostream & COUT,const Vector<Tipo> &W)
{
COUT << '(';
for(int i = 0;i < W.dim ;i++) COUT << W.V[i] << ',';
COUT<<"b)";
return COUT;
}
friend istream& operator>>(istream & CIN,Vector<Tipo> &W)
{
for(int i = 0;i < W.dim ;i++){
cout<<"Ingrese la componente " << i + 1<< " del vector." << endl;
CIN>>*(W.V+i); // W.V[i]
}
return CIN;
}
friend Vector operator*(Tipo esc, const Vector<Tipo> &W)
{
return W*esc;
}
public:
explicit Vector(int dim)
{
if(dim>0){
V = new (nothrow) Tipo[dim];
for(int i=0;i<dim;++i) V[i]=0;
}
}
Vector(const Vector<Tipo> &W)
{
dim=W.dim;
if(dim){
V=new (nothrow) Tipo[dim];
for(int i=0;i<dim;++i) V[i]=W.V[i];
}
}
~Vector()
{
if(V){
dim=0;
delete [] V;
}
}
Vector operator+(const Vector<Tipo> &W) const
{
Vector S(dim);
for(int i = 0;i < dim;i++){
S.V[i] = V[i] + W.V[i];
}
return S;
}
private:
Tipo *V;
int dim;
};
int main()
{
int dim;
float pEscalar, numEscalar;
cout << "Programa que calcula la suma de dos vectores en R^n, n>0" << endl;
do
{
cout << "n: ";
cin >> dim;
}while(dim <= 0);
Vector<float> V(dim) ,W(dim),S(dim),R(dim);
cout<<"Primer vector..." << endl;
cin>>V;
cout<< endl << endl << "Segundo vector..." << endl;
cin>>W;
S=V+W;
cout << endl << "La suma del primer y segundo vector es: " << endl;
cout<<V<<" + "<<W<<" = "<<S<<endl;
cout << endl;
system("pause");
return EXIT_SUCCESS;
}
看看你的 Vector 构造函数,它有一个 int 参数:
explicit Vector(int dim)
{
if (dim>0){
V = new (nothrow) Tipo[dim];
for(int i=0;i<dim;++i) V[i]=0;
}
}
// So where do you assign the dim value in your object??
将 dim 分配给对象的位置? 这是你想做的,以解决你的直接问题,但我还要声明你的班级还有其他问题需要另一个讨论线程。
explicit Vector(int dim_) : dim(dim_)
{
if (dim>0){
V = new (nothrow) Tipo[dim];
for(int i=0;i<dim;++i) V[i]=0;
}
}
另外,为什么不使用调试器? 如果使用调试器运行代码,则在执行此行后几秒钟内应该会发现问题:
Vector<float> V(dim) ,W(dim),S(dim),R(dim);
你会看到V.dim,W.dim等是垃圾值。
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么