简体   繁体   English

C ++模板:无法从main.cpp调用我的函数

[英]C++ template: cannot call my function from main.cpp

This question may get thrown out but I've been searching and searching for help on this. 这个问题可能会抛出,但我一直在寻找有关此方面的帮助。 I am a total beginner.. OK: I have a template class with a function that adds two vectors and outputs to a 3rd vector. 我是一个初学者。OK:我有一个模板类,其函数将两个向量相加并输出到第三个向量。 I need to call if from my main program. 我需要从主程序中调用。 Here is my template (very simple). 这是我的模板(非常简单)。

#include <vector>
#include<iostream>
#include<iomanip>
#include<algorithm>
using namespace std;

template<class T>
class polyClass {
public:
    //position 0 always constant, pos1 x^1, pos2 x^2
    vector<T> a;
    vector<T> b;
    vector<T> result;

    int addVectors(T& a, T& b, T& result) {

        for (vector<T> i = a[i].begin; i != a[i].end(); i++) {

            result[i] = a[i] + b[i];
            return result;

        }
    }
};

I need to call the addVectors function from my main program. 我需要从主程序调用addVectors函数。 And I keep getting the message that I did not declare 'a', 'b', and 'result' in this scope.I am going on 3 hours with this and could really use some help. 而且我不断收到这样的信息,我没有在此范围内声明'a','b'和'result'。我为此进行了3个小时的尝试,确实可以使用一些帮助。 Here is my main program. 这是我的主程序。

#include <iostream>
#include<vector>
using namespace std;
#include "PolynomMult_Add.h"

int main() {

    polyClass<int> newPolyClass;
    newPolyClass.a = {3, 4, 2};
    newPolyClass.b = {3, 3, 1};
    newPolyClass.result = {};

    newPolyClass.addVectors(a, b, result);


    return 0;
}

You were getting undeclared variables because you need to use newPolyClass.a, newPolyClass.b, newPolyClass.result instead of a, b and resullt. 之所以得到未声明的变量,是因为您需要使用newPolyClass.a,newPolyClass.b,newPolyClass.result而不是a,b和resullt。 Here is corrected code. 这是更正的代码。

#include <vector>
#include<iostream>
#include<iomanip>
#include<algorithm>
using namespace std;

template<class T>
class polyClass {
public:
    //position 0 always constant, pos1 x^1, pos2 x^2
    vector<T> a;
    vector<T> b;
    vector<T> result;

    vector<T> addVectors(vector<T> & a, vector<T> & b, vector <T> & result) {

        for (auto i = a.begin(), j = b.begin(); i != a.end() && j != b.end(); i++, j++) {

            result.push_back (*i + *j);

        }
        return result;
    }
};


int main() {

    polyClass<int> newPolyClass;
    newPolyClass.a = {3, 4, 2};
    newPolyClass.b = {3, 3, 1};
    newPolyClass.result = {};

    newPolyClass.addVectors(newPolyClass.a, newPolyClass.b, newPolyClass.result);


    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM