单独文件中的 C++ 类无法编译。已经在 Class.obj 中定义了一个或多个多重定义的符号

标签 c++ file class oop compiler-errors

所以我在 StackOverflow 上进行了广泛的谷歌搜索和搜索,尽管针对这个确切问题有多个答案,但我无法找到解决方案。

我正在尝试在名为 Fpc5.cpp 的外部文件中创建一个测试类

它的内容是:

Fpc5.cpp

#include "stdafx.h"
#include "Fpc5.h";
#include <iostream>
using std::cout;

class Fpc5 {
    int bar;
public:
    void testMethod();
};

void Fpc5::testMethod() {
    cout << "Hey it worked! ";
}

和我的主要 .cpp 文件:

测试.cpp

// Test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
//#include "Fpc5.cpp"
#include "Fpc5.h";
using std::cout;
using std::cin;
using std::endl;

int main()
{
    cout << "Hello" << endl;
    Fpc5 testObj;
    testObj.testMethod();

    system("pause");
    return 0;
}

我读过的所有答案都表明这是因为我曾经在主文件本身中包含类,这就是我创建头文件的原因

Fpc5.h

#pragma once
void testMethod();

这改变了错误,但仍然没有解决问题。目前我的 Test.cpp 无法识别 Fpc5 类。我也尝试在 stdafx.h 中添加 Fpc5.cppFpc5.h ,但仍然没有解决问题。

stdafx.h

// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

// TODO: reference additional headers your program requires here

//#include "Fpc5.cpp"
#include "Fpc5.h"

我确定这是一个简单的语法/概念理解错误,但我对 c++ 很陌生,不确定哪里出了问题。

最佳答案

这是你的类的定义,它必须在 Fpc5.h 中

class Fpc5 {
    int bar;
public:
    void testMethod();
};

然后,您有 Fpc5.cpp,您可以在其中实现类的方法:

#include "Fpc5.h" // Compiler needs class definition to compile this file!

void Fpc5::testMethod()
{
}

然后你可以在Test.cpp中使用Fpc5类

#include "Fpc5.h"

int main()
{
    Fpc5 foo;
    foo.testMethod();
    return 0;
}

作为替代方案,您可以将所有内容打包到 Test.cpp 中

关于单独文件中的 C++ 类无法编译。已经在 Class.obj 中定义了一个或多个多重定义的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39542561/

相关文章:

c++ - 按递增顺序枚举代数表达式

php - 超过最大文件大小不显示错误

java - 公共(public) Java 类或 Jar

c++ - 将包含数组的结构推送到 vector 中

c++ - Qt设置QLineEdit的背景颜色

c# - 从文件读取时,Number 拒绝从字符串转换为 int (C#)

file - 如何使用groovy从目录中获取最新文件?

C++ 嵌套类让我发疯

c++ - 在一个函数中使用类的每个成员来计算平均值

c++ - 不希望 main 等待 boost 线程完成吗?