C ++ main.cpp编译错误

时间:2013-09-20 02:48:12

标签: 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);
};

3 个答案:

答案 0 :(得分:2)

尝试在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文件中。 Hoewever,这不是强制性的,您可以将内容放在.h文件中。

要使代码编译,请用完整的函数替换函数声明:

bool TestAdd();

成为:

bool TestAdd(){return true;}

希望这有帮助

答案 1 :(得分:0)

我认为这是链接器错误。对于每个班级,您应该将它们作为来源添加。

如果你正在使用gnu编译器,这里有一个makefile:

CC=g++
CFLAGS=-c -Wall -pedantic
LDFLAGS=
SOURCES=main.cpp test.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=programname

all: $(SOURCES) $(EXECUTABLE)

$(EXECUTABLE): $(OBJECTS) 
    $(CC) $(LDFLAGS) $(OBJECTS) -o $@

.cpp.o:
    $(CC) $(CFLAGS) $< -o $@

clean:
    rm -rf *o programname

答案 2 :(得分:0)

有一个主要的,

   int main(){

       bool add, sub, transp, mult, multScal;

       Test ObjTest;// Object for Test class created
       //Checks each operation at once, some should fail each time depending on contents of C.txt
       add=objTest.TestAdd(); //Accessing the member function using Object

       sub=objTest.TestSubtr();

       transp=objTest.TestTranspose();

       mult=objTest.TestMultMatrices();

       multScal=objTest.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 laying!";
   }

解决方案是您必须创建类Test的对象才能访问成员函数。

希望这有帮助。