2016-09-17 12 views
1

因此,我已經在StackOverflow上進行了大量的搜索和搜索,並且無法找到一個解決方案,儘管這個確切問題有幾個答案。單獨文件中的C++類未編譯。已經在Class.obj中定義了一個或多個找到的多重定義符號

我想在外部文件中創建一個測試類叫做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文件:

Test.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; 
} 

所有我讀過的答案表明,這是becaused我以前是包括在主文件本身的類,這是爲什麼我創建了一個頭文件

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++,我不知道什麼是錯的。

+0

您的類定義需要在標題中,而不是源文件中。 – 1201ProgramAlarm

回答

1

這是你的類的定義,它必須在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() 
{ 
} 

然後你可以使用Fpc5類Test.cpp的

#include "Fpc5.h" 

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

作爲替代你可以打包到一切Test.cpp的

+0

這確實允許我的Test.cpp識別一個Fpc5對象,但是現在當我嘗試編譯時,我得到了2個錯誤:「function_main中引用的未解析的外部符號」和「1個未解析的外部」有關於這些的任何想法? – kalenpw

+0

我只需要清理並重建我的解決方案。感謝你及時的答覆。 – kalenpw

1

移動類的定義:

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

的頭文件, 「Fpc5.h」。

實施方法爲「Fpc5.cpp」。

相關問題