在头文件中声明类对象 [英] Declaring class objects in a header file

查看:302
本文介绍了在头文件中声明类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给每个人打招呼。

我似乎陷入了一个基金会,但我无法在任何地方找到解决方案。任何人,将继续解释。



我有一个由三个文件组成的程序; main.ccp,add.h,add.cpp。



我在add.h中声明了类SA,并且在add.cpp中定义了所有的函数。 p>

additional.h

  class SA {
...
public
int x;
} Obj1,Obj2;

main.ccp

  #includeadditional.h

int main(){

Obj1.x = 5;

...
}

这给了我一个链接编译时出错:
错误LNK2005:已在main.obj中定义的class SA Obj1(?Obj1 @@ 3VSA @@ A)

唯一的定义的对象出现在add.h中,而没有其他地方出现。如果在main和header中声明对象,程序编译就好了:

main.ccp

 #includeadditional.h

int main(){

SA Obj1;
Obj1.x = 5;

...
}

问题是我想要在add.cpp中主要使用对象,但仍需要通过main.cpp初始化多个公共值。任何智慧之语?

解决方案

在您的.cpp中声明Obj1和Obj2而不是.h



add.h

  class SA {
...
public
int x;
};

main.cpp

  #includeadditional.h

SA Obj1,Obj2;

int main(){

Obj1.x = 5;

...
}

如果你想声明Obj1和Obj2在你的.h文件中,在.h文件中添加extern就像这样:

  extern SA Obj1,Obj2; 

但您应该在项目中的.cpp文件中声明对象:



main.cpp

  SA Obj1,Obj2; 

原因是每次包含.h文件时,都声明了Obj1和Obj2。因此,如果您包含.h文件两次,您将创建Obj1和Obj2的两个实例。通过添加关键字extern,您告诉编译器您已经在项目的某个地方(最好在.cpp文件中)中放置了两个变量。


Greetings everyone.

I seem to be snagging on a fundimental but I cant find the solution anywhere. Anywho, will go ahead and explain.

I have a program consisting of three files; main.ccp, add.h, add.cpp.

I declare the class 'SA' in add.h and have all my functions defined in add.cpp

additional.h

class SA {
    ...
public
    int x;
} Obj1, Obj2;

main.ccp

#include "additional.h" 

int main() {

    Obj1.x = 5;

    ...
}

This gives me a link error on compiling: error LNK2005: "class SA Obj1" (?Obj1@@3VSA@@A) already defined in main.obj

The only deffinition of the object occurs in add.h, and no where else. The program compiles just fine if declare the objects in the main and not the header:

main.ccp

#include "additional.h" 

int main() {

    SA Obj1;
    Obj1.x = 5;

    ...
}

The issue is that I want to use the objects primarially within add.cpp, but still need to initialise several public values through main.cpp. Any words of wisdom?

解决方案

Declare Obj1 and Obj2 in your .cpp instead of at .h

add.h

class SA {
 ...
public
    int x;
};

main.cpp

#include "additional.h" 

SA Obj1, Obj2;

int main() {

 Obj1.x = 5;

 ...
}

If you want to declare Obj1 and Obj2 in your .h file, add extern in the .h file like so:

extern SA Obj1, Obj2;

but you should declare the objects in a .cpp file in your project:

main.cpp

SA Obj1, Obj2;

The reason for this is that everytime you include the .h file, you are declaring Obj1 and Obj2. So if you include the .h file two times, you will create two instance of Obj1 and Obj2. By adding the keyword extern, you are telling the compiler that you have already decalred the two variables somewhere in your project (preferably, in a .cpp file).

这篇关于在头文件中声明类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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