C ++如何调用使用向量的成员函数

我目前正在尝试通过调用dotProduct函数来显示点积,但是我对如何执行此操作感到困惑。我试过调用该函数,但由于它不起作用而将其注释掉。显示点积的正确方法是什么?任何帮助将不胜感激!

#include <iostream>
#include <vector>
#include <ctime>
#include <iomanip>
using namespace std;
class list
{
    public:
        list();
        void input(int s);
        void output();
        double dotProduct(vector <double> a,vector <double> b);
    private:
        vector <int> v;
};
list :: list() : v()
{
}
void list :: input(int s)
{
    int t;
    for(int i = 1; i <= s; i++)
    {
        t = rand() % 10;
        v.push_back(t);
    }
}
void list :: output()
{
    for(unsigned int i = 0; i < v.size(); i++)
        cout << v[i] << " ";
    cout << endl;
}
double list :: dotProduct(vector <double> a,vector <double> b)
{
    double product = 0;
    if(a.size() != b.size())
    {
        cout << "Vectors are not the same size\n";
    }
    for (unsigned int i = 0; i < a.size(); i++)
    {
        product = product + a[i] * b[i];
    }

    return product;

}
int main()
{
    list L1,L2,ob1;
    int s;
    cout << "Enter the size of list 1: \n";
    cin >> s;
    L1.input(s);
    cout << "\nEnter the size of list 2: \n";
    cin >> s;
    L2.input(s);
    cout << "\nVector 1: ";
    L1.output();
    cout << endl;
    cout << "Vector 2: ";
    L2.output();
    cout << endl;

    cout << "The dot product is: ";
    //ob1.dotProduct(L1.output(),L2.output());
    cout << endl;   

    return 0;

}
QQ170102852 回答:C ++如何调用使用向量的成员函数

dotProduct ()确实看起来不像成员函数。它不访问任何实例数据。如果需要,可以将其定义为一个接受两个向量并计算点积的常规函数​​。

如果要使用两个列表L1和L2中的向量调用此函数(为什么它不是列表,为什么要调用“列表”类?),则需要公开实际的向量通过公开它来创建“ v”,或者创建一个返回它的“ getter”成员函数。 dotProduct()函数不返回类实例或向量,而返回标量值。

另一种方法是定义一个类成员函数,该成员函数在一个类实例上运行,并以第二个类实例作为参数。签名就像

list::dotProduct (list arg);

这将计算“ this”实例与参数arg的点积。

它将被称为

cout << L1.dotProduct (L2);
本文链接:https://www.f2er.com/3106101.html

大家都在问