不能在C ++中从main实例化另一个类 [英] Can not instantiate another class from main in C++

查看:106
本文介绍了不能在C ++中从main实例化另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些是我的文件。我试图打印一行使用另一个类从main.cpp但它给一个错误未定义的引用poddy:poddy()



main.cpp

  #include< iostream> 
#includepoddy.h

using namespace std;

int main(){
poddy le;
return 0;
}



poddy.h

  #ifndef PODDY_H 
#define PODDY_H

class poddy {
public:
poddy
};

#endif // PODDY_H

poddy.cpp

  #includepoddy.h
#include< iostream>

using namespace std;

poddy :: poddy(){
cout<< I am llalala and use anoder class< endl;
}

请帮助我!

解决方案

您的C ++代码是正确的。 未定义的引用是一个链接器错误,与编译代码的方式有关。要使其链接,请使用以下命令行:

  g ++ poddy.cpp main.cpp 

以下是详细信息:编译C ++代码的过程有三个主要阶段 - 预处理,编译和链接。预处理器处理代码中的 #define #include 语句。编译器获取预处理的结果,并为每个翻译单元生成二进制代码(在您的情况下,有两个翻译单元 - poddy.cpp main .cpp )。最后,链接器在翻译单元内建立二进制代码部分之间的连接。



预处理器和编译器即使在一次提供一个翻译单元时也能完成他们的工作。然而,链接器必须一次看到所有翻译单元。当调用 g ++ 而没有其他标志时,将调用编译器的所有阶段,包括链接器。这就是为什么您需要一次列出所有翻译单位。


These are my files. I am trying to print a line using another class from main.cpp but it gives an error "undefined reference to poddy:poddy()"

main.cpp

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

using namespace std;

int main() {
    poddy le;
    return 0;
}

poddy.h

#ifndef PODDY_H
#define PODDY_H

class poddy {
    public:
        poddy();
};

#endif // PODDY_H

poddy.cpp

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

using namespace std;

poddy::poddy() {
    cout << "I am llalala and use anoder class" << endl;
}

Please help me out!

解决方案

Your C++ code is correct. The "undefined reference" is a linker error that has to do with the way you are compiling your code. In order for it to link, use this command line:

g++ poddy.cpp main.cpp

Here are the details: the process of compiling C++ code has three major stages - preprocessing, compiling, and linking. Preprocessor deals with #define and #include statements in your code. Compiler takes the results of preprocessing, and produces binary code for each translation unit (in your case, there are two translation units - poddy.cpp and main.cpp). Finally, the linker establishes connections between parts of binary code within translation units.

The preprocessor and the compiler can do their job even when presented with one translation unit at a time. The linker, however, must "see" all translation units at once. When you call g++ without additional flags, all stages of the compiler are invoked, including the linker. That's why you need to list all translation units at once.

这篇关于不能在C ++中从main实例化另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆