成员引用基类型"矩阵(向量 &,向量 &)不是结构或联合
Member Reference base type 'Matrix(Vector &, Vector &) is not a structure or union
当我尝试使用void print函数时,我收到错误"Member Reference base type'Matrix(Vector&,Vector&aamp;)不是结构或并集"。这个程序应该从用户那里获取值并将其存储在数据阵列中,然后它获取向量a和向量b并进行向量乘法以打印矩阵a。
#include <iostream>
using namespace std;
const int rows=3;
const int columns=3;
const int elements=3;
class Vector{
private:
double data[elements];
public:
Vector();
void read();
double get_element(int);
};
Vector::Vector(){
int i=0;
while(i<elements){data[i++]=0;}
}
Vector a;
Vector b;
Vector c;
Vector d;
void Vector::read(){
int j=0;
cout<<"Enter "<<elements<<" elements of vector a"<<endl;
while(j<elements){cin>>data[j++];}
}
double Vector:: get_element(int n){
while(n<elements)
return data[n];
}
class Matrix {
private:
double data [rows*columns];
public:
Matrix(Vector &, Vector &);
void add (const Matrix &);
void mult (double);
double trace();
double norm();
void print ();
};
Matrix::Matrix(Vector &, Vector &){
int d,f;
for (d=0; d<(rows); d++){
for (f=0; f<columns;f++){
data[d*f]=a.get_element(d)*b.get_element(f);
}
}
}
Matrix A (Vector &a, Vector &b);
Matrix B (Vector &c, Vector &d);
void Matrix::print(){
cout.precision(3);
for (int i=0; i<rows; i++) {
cout << endl;
for (int j=0; j<columns; j++) {
cout << " " << data[i*j];
}
//This is printing Matrix A.
}
}
int main(){
a.read();
b.read();
c.read();
d.read();
A.print();
//The error occurs here.
return 0;
}
如果您试图将A和B定义为全局变量,请更改Matrix A (Vector &a, Vector &b);
Matrix B (Vector &c, Vector &d);
至Matrix A (a, b);
Matrix B (c, d);
A和B是函数名。功能被声明为
Matrix A (Vector &a, Vector &b);
Matrix B (Vector &c, Vector &d);
在这些声明中,a和b被视为函数参数。
所以在这个声明中
A.print();
编译器将A作为函数名进行处理。
我想你是指
Matrix A (a, b);
Matrix B (c, d);
编辑:这是你的评论的答案。
类向量具有默认构造函数
Vector::Vector(){
int i=0;
while(i<elements){data[i++]=0;}
}
如果数据成员数据为零,则设置所有元素。
您使用默认构造函数创建了Vector类型的对象
Vector a;
Vector b;
Vector c;
Vector d;
然后使用这些矢量创建了矩阵类型的对象A和B。
Matrix A (a, b);
Matrix B (c, d);
所以这些对象包含零。
您应该删除这些定义并写入主
int main()
{
Vector a, b, c, d;
a.read();
b.read();
c.read();
d.read();
Matrix A( a, b );
Matrix B( c, d );
A.print();
return 0;
}
顺便提一下,构造函数
Matrix::Matrix(Vector &, Vector &){
int d,f;
for (d=0; d<(rows); d++){
for (f=0; f<columns;f++){
data[d*f]=a.get_element(d)*b.get_element(f);
}
}
无效。它有两个参数,但它们没有在构造函数的主体中使用。局部变量d和f也没有初始化。
相关文章:
- 将结构向量排序为子组
- 访问存储在向量C++中的结构的多态成员
- NLOHMANN 的 JSON 库将数组转换为结构向量
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 如何在 c++ 中创建结构向量的映射
- 带unique_ptr的结构向量
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 将 int 映射到 C++ 中的向量结构
- 如何在 c++ 中的向量结构中使用结构向量
- 无法将值存储到向量结构中
- 无法将.CSV文件读取为代表向量结构的类
- MPI,C,派生类型,向量结构
- 向量结构的打印成员
- 在 c++ 中对向量<结构 S> 进行二分搜索?
- 不需要删除向量<结构A*>
- 在C++中循环向量结构<string>
- 将字符串放入字符串的向量结构中
- 共享内存中的向量结构
- 我的向量结构没有像预期的那样迭代