之前的预期主要表达。在调用类函数时

时间:2014-03-22 17:17:07

标签: c++ class

对于课程,我们正在制作一个分析和经验计算T(n)的程序。我们的函数应该在一个单独的类f中,我们应该使用一个函数来读取文件中的输入以用作" n"并调用函数来打印值。当我尝试将分析函数作为打印函数的参数调用时,我收到此错误:

p03.cpp:61:23: error: expected primary-expression before â.â token
p03.cpp:61:34: error: expected primary-expression before â.â token

我确信这是一个愚蠢的错字,但我无法找到它。是的,我在p03.cpp和F03.cpp中包含了F03.h。以下是导致错误的代码:

void analysis(istream& i) {

//Code Fragment 0 analysis
PrintHead(cout, "Code Fragment 0");
for(;;) {
    int n;
    i >> n;
    if (i.eof()) break;
            //Next line is line 61
    PrintLine(cout, n, f.af00(n), f.ef00(n));
}
}

以下是p03.cpp中的打印功能:

    void PrintHead(ostream& o, string title) {
        o << title << endl;
        o << setw(20) << "n" << setw(20) << "Analytical" << setw(20) << "Empirical";
        o << endl;
    }

    void PrintLine(ostream& o, int n, int a, int e) {
        o << setw(20) << n << setw(20) <<a << setw(20) << e << endl;
    }

这是F03.h中f的类声明:

#ifndef F03_h
#define F03_h 1

#include <cstdlib> 
#include <cstring> 
#include <iostream> 
#include <fstream> 
#include <string> 

class f {

    public:
int ef00(int n);

int af00(int n);

};

#endif

以下是实施:

                            #include <cstdlib> 
            #include <cstring> 
            #include <iostream> 
            #include <fstream> 
            #include <string> 

            #include "F03.h"

            int f::ef00(int n) 
                { int t=0; 
                int sum=0; t++; 
                 int i=0; t++; 
                 while (i<n) { t++; 
                 sum++; t++; 
                 i++; t++; 
                 } t++; 
                 return t; 
                } 

            int f::af00(int n) 
                { return 3*n+3; 
                } 

非常感谢任何见解!

2 个答案:

答案 0 :(得分:5)

f::af00f::ef00是类f的非静态成员,因此您需要在实例上调用它们。例如

f myf;
PrintLine(cout, n, myf.af00(n), myf.ef00(n));

或者,将方法设为静态,并将其称为f::af00(n)等。

class f 
{
 public:
  static int ef00(int n);
  static int af00(int n);
};

然后

PrintLine(cout, n, f::af00(n), f::ef00(n));

答案 1 :(得分:1)

当您调用PrintLine时,看起来您正在尝试将非静态函数作为静态函数调用。具体来说f.af00(n); f是类的名称,但您使用它就像变量的名称一样。

可能您打算将类f中的函数声明为静态函数,因为f没有任何数据成员。如果您这样做,则会将该函数调用为f::af00(n)

有关静态函数概念的更多信息,请参阅此问题:What is a static function?

相关问题