C++ 错误,未定义的引用类

2023-01-21C/C++开发问题
4

本文介绍了C++ 错误,未定义的引用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

为什么代码块会给出这个错误未定义对 class::classfunction() 的引用"在一个单独的文件中创建一个类时会发生这种情况.所有这些文件都在同一个文件夹中

Why does codeblocks give this error "Undefined reference to class::classfunction()" It happens when a class is created in a separated file.All of these files are in the same folder

这是主要的 .cpp 文件

This is the main .cpp file

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

using namespace std;

main()
{
    Class2 classObject;
    cout<<"I'm class2"<<endl;

}

类头文件

#ifndef CLASS2_H
#define CLASS2_H


class Class2
{
    public:
        Class2();
        ~Class2();
    protected:
    private:
};

#endif // CLASS2_H

类cpp文件

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

using namespace std;

Class2::Class2()
{
    cout<<"Hello, I'm Constructor"<<endl;
}

Class2::~Class2()
{
    cout<<"Yo!! I'm Destructor"<<endl;
}

错误是对 Class2::Class2() 的未定义引用"

error is "undefined reference to Class2::Class2()"

推荐答案

您需要将 main.oclass.o 链接到您的可执行文件中.确切的命令取决于您的编译器和操作系统.对于 g++ 命令看起来像

You need to link both main.o and class.o into your executable. The exact command depends on your compiler and OS. For g++ the command would look something like

g++ -o main main.cpp class.cpp

这篇关于C++ 错误,未定义的引用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6