定义一个全局类对象 [英] defining a global class object

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

问题描述

嗨 我创建了此文件

 //  lib.cpp 
#include   "  lib.h" 

 myclass
{
    公共:
         int  ;
};

myclass m1; 





 //  lib.h 
#ifndef LIB_H_INCLUDED
 #define LIB_H_INCLUDED

 class  myclass;
 外部 myclass m1;

#endif//LIB_H_INCLUDED  



主文件

 #include   ><   iostream  > 
 #include   " 
 使用 命名空间 std;

 int  main()
{
    m1. =  10 ;
    cout<< m1.;
    返回  0 ;
} 



但是编译器在主文件中给出错误,指出m1对象是不完整的类型,无法创建.
如何定义类的全局对象并在项目中使用它?

解决方案

问题是,类本身定义的唯一位置是在"Lib.CPP"文件,因此没人知道它有多大.主要通过"lib.h"知道的唯一事情是,有一个名为"myclass"的类,并且只有部分定义(即它存在),但没有其他信息,因此是不完整的类型.

您需要在lib.h中包含该类的完整定义.

如果您使用指向类的指针",则只能使用部分定义"(即,仅使用"class myclass;"语句),因为知道指针的大小而不管该类的大小.当然,如果要使用指针,则还需要更改其他内容.


您的主体应该是

 #include   ><   iostream  > 
 #include   " 
 使用 命名空间 std;
   外部 myclass m1; 
 int  main()
{
    m1. =  10 ;
    cout<< m1.;
    返回  0 ;
} 


hi i created this files

//lib.cpp
#include "lib.h"

class myclass
{
    public :
        int value;
};

myclass m1;



and

//lib.h
#ifndef LIB_H_INCLUDED
#define LIB_H_INCLUDED

class myclass;
 extern  myclass m1;

#endif // LIB_H_INCLUDED



main file

#include <iostream>
#include "lib.h"
using namespace std;

int main()
{
    m1.value=10;
    cout<<m1.value;
    return 0;
}



but compiler gives an error in the main file that the m1 object is incomplete type and can not be created.
how can i define a global object of my class and use it in my projects?

解决方案

The problem is that the only place the class itself is defined is in the "Lib.CPP" file so noone knows how big it is. The only thing main knowns, via "lib.h" is that there is a class named "myclass" and there is only a partial definition (i.e., it exists) but no other information, therefore an incomplete type.

You''ll need to include the full definition of the class in lib.h.

You can only use the "partial definition" (i.e, just the "class myclass;" statement) if you are using "pointers to the class" since the size of a pointer is known regardless of how big the class is. Of course, if you want to use pointers, there are other things you''ll have to change.


Your main should be,

#include <iostream>
#include "lib.h"
using namespace std;
extern  myclass m1;
int main()
{
    m1.value=10;
    cout<<m1.value;
    return 0;
}


这篇关于定义一个全局类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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