【问题标题】:Multiple files function calls C++多文件函数调用 C++
【发布时间】:2015-01-09 03:52:16
【问题描述】:

我正在编写一个计算向量范数的程序(与自身的点积)。 我实现代码没有问题,我不能做的是从除主函数之外的函数调用函数。

header.h

#ifndef HEADER
#define HEADER

void readArray(double [], int &);
void printArray(double [], int &);
void norm(double [], int &);
double scalarProduct(double [], int &);

#endif

norm.cc

// norm.cc
#include <iostream>
#include <cmath>
using namespace std;

void norm(double array[], int & size)
{
    double norm;
    norm = sqrt(scalarProduct(array, size));

    cout << "Norm = " << norm << endl;
}

scalarProduct.cc

// scalarProduct.cc
#include <cmath>
double scalarProduct(double array[], int & size)
{
    double ps = 0.0;
    for(int i = 0; i < size; i++)
    {
        ps += pow(array[i], 2);
    }
}

在 main.cc 文件中我添加了这一行

#include "header.h"

我从 main 调用的所有函数都像魅力一样工作,但是从 norm() 调用 productScalar() 不起作用。我添加了相同的#include "header.h" 行,但编译器说我不能多次定义同一个函数。我该如何解决这个问题?

【问题讨论】:

  • 您可能想更深入地了解 OOP 的工作原理:cplusplus.com/doc/tutorial/classes
  • 如果您不更改它的值,我不会将 int 作为引用传递给函数。
  • 应该可以。说出“不起作用”的意思并发布编译器的 exact 错误消息。 (顺便说一句:您忘记从 scalarProduct 返回任何内容,为什么 size 参数是参考?)
  • 您忘记将结果返回到scalarProduct
  • norm.cc 也应该有 #include "header.h"

标签: c++ arrays file function include


【解决方案1】:

添加 #include "header.h" 进入 norm.cc

【讨论】:

  • 谢谢,它成功了。我很困惑,因为我确定我试过了,但是编译器会返回同样的错误......我一定做错了什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-02
  • 2017-06-09
  • 2020-07-09
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
相关资源
最近更新 更多