【发布时间】: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