【问题标题】:C++ How to call a member function that uses vectorsC++如何调用使用向量的成员函数
【发布时间】:2019-11-13 23:52:13
【问题描述】:

我目前正在尝试通过调用 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;

}

【问题讨论】:

  • list::output()的返回值没有vector的类型。您不能将它传递给需要一个的函数。
  • 无关:当你走到这一步时,你可能会在double dotProduct(const vector &lt;double&gt; &amp; a, const vector &lt;double&gt; &amp; b);中发现一些额外的效率和多功能性

标签: c++ class for-loop vector dot-product


【解决方案1】:

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

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

另一种方法是定义一个类成员函数,该函数对一个类实例进行操作,并将第二个类实例作为参数。签名将类似于

list::dotProduct (list arg);

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

它会被调用

cout << L1.dotProduct (L2);

【讨论】:

猜你喜欢
  • 2014-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 2011-08-15
  • 1970-01-01
  • 2013-01-26
相关资源
最近更新 更多