我类的每个函数都给我这个错误。我将以我的 3 参数构造函数为例:
#include <iostream>
using namespace std;
class Mixed{
public:
Mixed(int i, int n, int d);
private:
int integer, numerator, denominator;
};
还有我的cpp:
#include "mixed.h"
#include <iostream>
#include <iomanip>
using namespace std;
Mixed::Mixed(int i, int n, int d){
int valid;
int negatives = 0;
if (d == 0){
valid = 0;
}
if (d < 0 | n < 0 | i < 0 && valid != 0){ //if there are any negatives and it hasn't been made invalid
if (i < 0){ //start counting negatives
negatives++;
}
if (n < 0){
negatives++;
}
if (d < 0){
negatives++;
}
if (negatives > 1){ //invalid if more than one negative value
valid = 0;
}
else {
valid = 1;
}
if (i != 0 && valid != 0){ //check for order if it hasn't already been made invalid
if (n < 0 | d < 0){ //invalid if integer is non zero, but one of the others is negative
valid = 0;
}
}
else if (n != 0 && d < 0){ //invalid if integer is zero, numerator is nonzero, and denominator is negative
valid = 0;
}
else if (valid != 0){ //if it hasn't already been invalidated, it's valid
valid = 1;
}
}
if (valid == 0){
this -> integer = 0;
this -> numerator = 0;
this -> denominator = 0;
}
else{
this -> integer = i;
this -> numerator = n;
this -> denominator = d;
}
}
正在使用我的类的 main.cpp 确实包含
#include <iostream>
#include "mixed.h"
using namespace std;
我的错误看起来像:
/tmp/ccbdj59O.o: 在函数 main': main.cpp:(.text+0x34): undefined reference to
Mixed::Mixed(int, int, int)'
我已经无计可施了,感觉这是一个明显的错误。想法?
最佳答案
您想编译两个 cpp 文件并将它们链接在一起。
这可以通过命令使用 g++ 来完成
g++ mixed.cpp main.cpp -o output_file
这会编译两个文件并将它们链接在一起。您也可以单独执行此操作:
g++ -c mixed.cpp -o mixed.o
g++ -c main.cpp -o main.o
g++ main.o mixed.o -o output_file
如果您不知道如何使用命令行,请查看 this tutorial 如果你在 Linux 上工作(我猜你是,基于你遇到链接器错误并因此让 g++ 工作的事实)。在 Windows 上,您可能希望使用 IDE ,看here寻求建议。
查看您正在使用 Sublime Text 构建文件的评论,也许尝试打开您的工作文件夹(文件 > 打开文件夹...)而不是单个文件。无论如何,我认为最好了解幕后发生的事情。
关于c++ - 我的一些函数出现 "undefined reference"错误,我不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37802285/