2

我正在学习 C++ 的一些基本概念,并且我被困在使用标头使用多个文件中。我有 3 个文件。

计算器.h

#ifndef CALCULATOR_H_CAL
#define CALCULATOR_H_CAL
class Calculator{
        int a,b;
        public:
        Calculator();
        Calculator(int,int);
    int op();
};
#endif

计算器.cpp

#include<iostream>
#include "Calculator.h"

    Calculator::Calculator(){
        a=0;b=0;
    }
    Calculator::Calculator(int c,int d){
        a=c;b=d;    
    }
    int Calculator::op(){
        return a*b;
    }

主文件

#include<iostream>
#include "Calculator.h"    

int main(){
    Calculator a(2,3);
    int b=a.op();
    std::cout << b;
}

但是用 g++ Main.cpp 编译会出错:

/tmp/cc09isjx.o: In function `main':
Main.cpp:(.text+0x83): undefined reference to `Calculator::Calculator(int, int)'
Main.cpp:(.text+0x8c): undefined reference to `Calculator::op()'
collect2: ld returned 1 exit status

这里有什么问题?

4

3 回答 3

4

你是如何编译代码的?我认为问题在于您在编译时没有将计算器文件与主文件链接。尝试这个:

g++ -c calculator.cpp
g++ main.cpp -o main calculator.o
于 2013-07-10T11:41:58.793 回答
1

如果您没有将文件与 main() 正确链接,那么您将无法正确编译它。

尝试这个-

g++ main.cpp 计算器.cpp

这现在应该包括您的头文件。

于 2013-07-10T12:32:03.050 回答
0

您可以使用以下命令进行编译:

g++ Main.cpp Calculator.cpp
于 2013-07-10T11:43:09.703 回答