1

I have a bit of code of the following format contained in a single .h and .cc file:

myClass.h:

#ifndef MYCLASS_H
#define MYCLASS_H
class myClass
{
public:
    myClass(); // constructor
    ~myClass(); // destructor

    void classMethod1 ();
    void classMethod2 ();

    int memberVarable1;
    int memberVariable2;
};
#endif

and myClass.cc:

#include "myClass.h"
myClass::myClass(){
 // stuff
}

myClass::~myClass(){
 // stuff
}

void myClass::classMethod1 (){
 // stuff
}

void myClass::classMethod2 (){
 // stuff
}

All of this is working fine. However my project is getting quite large and I'm about to add a set of new functionality. Instead of clogging up myClass.h and myClass.cc I want to put some new methods in another .cc file. I don't seem to be able to get this to work though.

myClass.h:

#ifndef MYCLASS_H
#define MYCLASS_H

#include "secondFile.h"

class myClass
    {
    public:
        myClass(); // constructor
        ~myClass(); // destructor

        void classMethod1 ();
        void classMethod2 ();

        int memberVarable1;
        int memberVariable2;
    };
#endif

and myClass.cc:

#include "myClass.h"
#include "secondFile.h"
myClass::myClass(){
 // stuff
}

myClass::~myClass(){
 // stuff
}

void myClass::classMethod1 (){
 // stuff
}

void myClass::classMethod2 (){
 // stuff
}

secondFile.h:

#ifndef SECONDFILE_H
#define SECONDFILE_H

void someNewMethod();

#endif 

secondFile.cc

#include "secondFile.h"
void someNewMethod(){
 // can't see classMethod1()
}
4

3 回答 3

3

在每个源文件中,您需要包含每个声明要使用的函数等的头文件。

因此,在您的情况下,您似乎希望 secondFile.cc 包含

#include "myClass.h"
#include "secondFile.h"
void someNewMethod(){
 // can't see classMethod1()
}

顺便说一句,您正在做的事情在实践中很常见。有时,我比您建议的更进一步,并在多个源文件中实现单个类的各种方法。对于大型、复杂的类,这有助于加快开发周期,因为如果我只进行了很小的更改,我只需要重新编译一小部分类实现。例子:

我的班级.h

#pragma once

class MyClass
{
  ...
  void complicatedMethod0();
  void complicatedMethod1();
  ...
};

myclass_impl0.cpp

#include "myclass.h"

void MyClass::complicatedMethod0()
{
  ...
}

myclass_impl1.cpp

#include "myclass.h"

void MyCLass::complicatedMethod1()
{
  ...
}
于 2013-04-23T21:55:54.663 回答
1

如果您打算向 中添加方法myClass,则不能这样做 - 类方法必须包含在一个定义中。

但是,您可以通过继承来扩展myClass

第二文件.h:

#ifndef SECONDFILE_H
#define SECONDFILE_H

#include "myClass.h"

class mySecondClass : public myClass
{
    public: 
        void someNewMethod();
}
#endif 

第二文件.cc

#include "secondFile.h"
void mySecondClass::someNewMethod(){
     this.classMethod1();
}
于 2013-04-23T22:03:40.723 回答
0
#include "secondFile.h"
#include "myClass.h" 
//if you want the class methods, 
//you need to tell the compiler where to look
void someNewMethod(){
 // can't see classMethod1()
}

您似乎忘记包含“myClass.h”。

于 2013-04-23T21:56:43.440 回答