简体   繁体   English

函数参数中的C ++类类型

[英]C++ class type in function parameters

Say I have two classes setup as shown below. 说我有两个类设置,如下所示。 Basically I want to pass the class1 object defined in main() to a method in the second class. 基本上,我想将main()中定义的class1对象传递给第二个类中的方法。 When I try to compile this, it says that class1 has not been declared. 当我尝试对此进行编译时,它表示尚未声明class1。 Can anyone explain why this doesn't work and how I can fix it? 谁能解释为什么这行不通以及如何解决?

//class1.h:

class class1
{
public:
    class1();
    void method1();
private:
    int myNumber;
};

//class1.cpp has the implementation for method1();

//class2.h:

class class2
{
public:
    class2();
    void method2(class1 myclass);
};

//class2.cpp:

#include "class1.h"
#include "class2.h"

int main( void )
{
    class1 myclass;
    class2 anotherClass;

    anotherClass.method2(myclass);

    return 0;
}

void class2::method2(class1 myclass)
{
    return;
}

You are missing the class keyword in your class definitions. 您在类定义中缺少class关键字。

instead of class1{...} you need class class1{...} , etc. 而不是class1{...}您需要class class1{...}等。

In class2.h , the compiler does not "know" how class1 is defined. class2.h ,编译器不“知道”如何定义class1 There are two possible solutions: 有两种可能的解决方案:

  • Add an #include "class1.h" in class2.h class2.h添加#include "class1.h"
  • Add a so-called forward declaration of class1 in class2.h by simply declaring class class1; 通过简单地声明class1class2.h添加class1的所谓前向声明 class class1; at the top of the header. 在标题的顶部。 You then need to change your method2 to either expect a reference or a pointer to class1 . 然后,您需要更改method2以期望引用指向 class1指针 If you then add #include "class1.h" in class2.cpp , everything will work. 如果然后在class2.cpp添加#include "class1.h" ,则一切正常。

the only clean solution is to include the header defining class class1 before the definition of class class2 . 唯一干净的解决方案是在class class2的定义之前包含定义class class1的标头。

Note that a forward declaration (al la Gnosophilon's answer) won't help here, as it only declares the class, but does not define it. 请注意,前向声明(按la Gnosophilon的回答)在这里无济于事,因为它仅声明该类,但未定义它。 This means that you can use a pointer or reference to the class, but not more, in particular you cannot pass class1 myclass by value as you try to do. 这意味着您可以使用指向类的指针或引用,但不能更多,尤其是在尝试执行操作时,不能按值传递class1 myclass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM