C++ main.cpp 编译错误

标签 c++ compilation

<分区>

(初学者)我的 main.cpp 在编译时遇到问题,这是我的情况:

#include <iostream>
#include <fstream>
#include "Test.h"

int main(){

bool add, sub, transp, mult, multScal;

//Checks each operation at once, some should fail each time depending on contents of C.txt
add=TestAdd();

sub=TestSubtr();

transp=TestTranspose();

mult=TestMultMatrices();

multScal=TestMultByScalar();

cout <<"Add success: " <<add <<'\n' <<"Subtract success: " <<sub <<'\n' 
<<"Transpose success: " <<transp <<'\n' <<"Multiplying 2 matrices success: " 
<<mult <<'\n' <<"Multiplying by Scalar success: " <<multScal <<"\nThanks for playing!";
}

TestAdd()TestSubtr() 等都可以在 Test.h 中找到。不过,我对每一个都收到了一个错误,说它们对于 main.cpp 是未定义的。关于为什么的任何线索?

编辑:这是我的 Test.h:

#include <iostream>
#include "Matrix.h"
class Test{
public:
    bool TestAdd();
    bool TestSubtr();
    bool TestTranspose();
    bool TestMultMatrices();
    bool TestMultByScalar(); 


private:
    Matrix loadMatrix(std::string filename);
    bool compare(Matrix A, Matrix B);
};

最佳答案

尝试将那些简单的函数定义放在 Test.h 中:

bool TestAdd() {return true;}
bool TestSubtr() {return true;}
bool TestTranspose() {return true;}
bool TestMultMatrices() {return true;}
bool TestMultByScalar() {return true;}

还要确保 Test.h 与 main.cpp 位于同一文件夹中。它应该编译没有错误。

编辑:

你面临的问题是你所有的测试函数都是类 Test 的成员,如果不创建 Test 类的实例就不能直接调用。您可以在 main() 中创建这样的实例:

Test myTest;

之后你可以在 main() 中像这样调用你的成员函数:

add = myTest.TestAdd();

此外,目前您的函数仅在 Test.h 中声明,但没有内容。函数内容放在方括号 { } 内。通常,您在 .h 文件中声明函数,并将函数内容放在 .cpp 文件中。但是,这不是强制性的,您可以将内容放在 .h 文件中。

为了让你的代码能够编译,用完整的函数替换你的函数声明:

bool TestAdd();

变成:

bool TestAdd(){return true;}

希望对你有帮助

关于C++ main.cpp 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18908070/

相关文章:

c++ - 加载所有 DLL 函数

c++ - 为什么我必须在这里使用dynamic_cast

c++ - 使用 Qt 制作静态构建(独立应用程序)

c - 将包含目录添加到 gcc *before* -I

c++ - c :\users be delete when delete windows account?下一个用户账号的文件夹怎么弄

c++ - 如果模板类型是可实例化的,则执行某些操作

macos - 在 64 位环境中编译 32 位 OS X 二进制文件

linux - 使用 Eclipse 从 Portaudio 编译 paex_record_file.c 时未定义对 `PaUtil_GetRingBufferReadAvailable' 的引用

ios - 当应用程序包中包含大量图像时,性能会受到影响

在 gtk+ 中编译单个测试