C++;如何引用其他类? 我是C++新手,设置一个简单的类引用有点麻烦。
类别:Test.hhC++;如何引用其他类? 我是C++新手,设置一个简单的类引用有点麻烦。,c++,class,object,reference,C++,Class,Object,Reference,类别:Test.hh #ifndef _TEST_HH_ #define _TEST_HH_ class Test { public: Test (double x); }; #endif Class Test.cc #include "Test.hh" #include <stdio.h> Test::Test(double x) { printf("%f",x); } 类DriverClass.cc #include "DriverClas
#ifndef _TEST_HH_
#define _TEST_HH_
class Test {
public:
Test (double x);
};
#endif
Class Test.cc
#include "Test.hh"
#include <stdio.h>
Test::Test(double x) {
printf("%f",x);
}
类DriverClass.cc
#include "DriverClass.hh"
DriverClass::DriverClass(double y) {
t = new Test(y);
}
但是,我得到一个错误:“未定义对'Test::Test(double)'的引用?”
有人知道可能有什么问题吗?请假设DriverClass是从主方法(未显示)直接调用的。您的帖子中仍然有错误-在
DriverClass之后有一个缺失的;
声明。其余的都是正确的
您应该编译并链接所有源代码
示例测试代码
生成文件
但是,请注意,通常建议将源代码单独编译为对象,以便只编译上次编译后更改的源代码。例如:
CFLAGS=-Wall -g
all: t
t: t.o DriverClass.o Test.o
g++ -o $@ $^
t.o: t.cc DriverClass.o Test.o
g++ $(CFLAGS) -c $< -o $@
DriverClass.o: DriverClass.cc
g++ $(CFLAGS) -c $< -o $@
Test.o: Test.cc
g++ $(CFLAGS) -c $^ -o $@
clean:
rm -f *.o t
测试
注意:不要忘记删除分配的对象。因为你没有链接两个编译的对象,你可以告诉我们你是如何调用编译器的(完整的命令行)
#包括“drivercasss.hh”-三重S
#如果ndef没有关闭,也可以#“当我将代码复制到stackoverflow时,#endif只是个错误。问题仍然存在same@UKMonkey你能解释一下吗?不知道我会不会跟上来谢谢!我忘了将新类添加到我的Makefile中
all: t
t: t.cc DriverClass.cc Test.cc
g++ -Wall -g -o $@ $^
clean:
rm -f *.o t
CFLAGS=-Wall -g
all: t
t: t.o DriverClass.o Test.o
g++ -o $@ $^
t.o: t.cc DriverClass.o Test.o
g++ $(CFLAGS) -c $< -o $@
DriverClass.o: DriverClass.cc
g++ $(CFLAGS) -c $< -o $@
Test.o: Test.cc
g++ $(CFLAGS) -c $^ -o $@
clean:
rm -f *.o t
#include "Test.hh"
#include "DriverClass.hh"
int main(int argc, char const* argv[])
{
DriverClass d(10.4);
return 0;
}
$ make
g++ -Wall -g -o t t.cc DriverClass.cc Test.cc
$ ./t
10.400000