我的代码存储在main.cpp
文件中,该文件包含void main()
函数和类MyClass
,我现在要将其拆分为另一个文件。 IDE是Microsoft Visual Studio 2008 Professional。
myclass.h
#include <tchar.h>
class MyClass {
public:
static bool MyFunction (TCHAR* someStringArgument);
};
myclass.cpp
#include <tchar.h>
class MyClass {
private:
static bool someProperty;
static void doSomeOneTimeCode () {
if (!someProperty) {
/* do something */
someProperty = true;
}
}
public:
static bool MyFunction (TCHAR* someStringArgument) {
doSomeOneTimeCode();
/* do something */
return true;
}
};
bool MyClass::someProperty = false;
main.cpp
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include "myclass.h"
void main () {
if (MyClass::MyFunction(TEXT("myString"))) {
_tprintf(TEXT("Yay\n"));
}
}
但是,当我尝试运行它时,我收到两个链接器错误。
MyClass::MyFunction
)如何防止这些链接器错误?
答案 0 :(得分:4)
你在这里宣布了两个班级。其中一个在 myclass.h 中,另一个在 myclass.cpp 中。请尝试以下方法:
#ifndef myclass_h_included
#define myclass_h_included
#include <tchar.h>
class MyClass {
private:
static bool someProperty;
static void doSomeOneTimeCode ();
public:
static bool MyFunction (TCHAR* someStringArgument);
};
#endif //!myclass_h_included
#include "myclass.h"
/*static*/ bool MyClass::someProperty = false;
void
MyClass::doSomeOneTimeCode() {
//...
}
bool
MyClass::MyFunction(TCHAR* someStringArgument) {
//...
}
您的 main.cpp 可以保持不变。我也会关注UncleBens回复。如果可能的话,应该隐藏一次初始化代码。
答案 1 :(得分:3)
哟不能在部分中拆分类定义。它必须在一个地方定义为一个整体。如果您想要定义类的某些方法,请创建一个MyClass
类稍后将继承的接口类。您应该将类的定义放在头文件(myclass.h)中,并将它的实现放在cpp文件(myclass.cpp)中。这样你可以在你的主cpp文件中包含“myclass.h”并在你的main函数中使用该类(应该是int main()
或int main( int argc, char *argv[] )
)。
答案 2 :(得分:2)
奇怪的是,您没有收到编译器错误,因为您正在重新定义MyClass。
定义(实现)进入cpp,它们的定义如下:
#include "myclass.h"
//helper functions, particularly if static, don't need to be in the class
//unnamed namespace means this stuff is available only for this source file
namespace
{
bool someProperty;
void doSomeOneTimeCode () {
if (!someProperty) {
/* do something */
someProperty = true;
}
}
}
bool MyClass::MyFunction (TCHAR* someStringArgument) {
doSomeOneTimeCode();
/* do something */
return true;
}