简体   繁体   English

C ++前向声明

[英]c++ forward declaration

#include <iostream>
#include <cstring>
using namespace std;

class Obj;


class Test {
    friend class Obj;
public:
    Test()
    {

    }
    ~Test()
    {

    }
    void foo()
    {
        //print();
            //Obj::print();
            //Obj x;
            //x.print();
    }
};

class Obj {
public:
    void print()
    {
        cout << "print here" << endl;
    }
};

int main()
{
    Test test;
    test.foo();
    return 0;
}

Quick question,how can I call print the correct way in Test::foo() ? 快速问题,如何在Test :: foo()中调用正确的打印方式?

You need to define the member function after the definition of Obj : 您需要 Obj定义之后定义成员函数:

class Test { 
public:
    void foo();
};

class Obj {
public:
    void print() { }
};

void Test::foo() { 
    Obj o;
    o.print();
}

As mentioned by james you should define the member function after the definition of Obj. 如james所述,您应该在Obj定义之后定义成员函数。 Also you are calling Obj::print, but print is not a static member function so you must call it on an instance of Obj not Obj itself. 另外,您正在调用Obj :: print,但是print不是静态成员函数,因此您必须在Obj实例而非Obj本身上调用它。

If you really do want print to be a static member, declare it so. 如果您确实希望print是静态成员,请声明它。

class Obj {
public:
    static void print(){ blah }
}

Also you do not need to make Obj a friend in order to access its public methods. 同样,您无需使Obj成为朋友即可访问其公共方法。

Also can OP please define "correct way", I was assuming you wanted it to be a static member function, james' answer is correct if you want one instance of Obj per instance of Test. 也可以OP请定义“正确的方式”,我假设您希望它是一个静态成员函数,如果您希望每个Test实例一个Obj实例,詹姆斯的答案是正确的。

UPDATED OP, as per your comment you must have the declaration of Obj along with print BEFORE using it within Test. 更新的OP,根据您的评论,在Test中使用Obj之前,必须先声明Obj以及打印。 This can be achieved in many ways: 这可以通过多种方式实现:

  • move the entire class Obj defintion (and declaration) before Test 在测试前移动整个类的对象定义(和声明)
  • declare Obj's methods with its class definition and define them later. 用其类定义声明Obj的方法,然后再定义它们。
  • declare Test like you have and Define Test as per James' post (after Obj). 像您一样声明Test并根据James的帖子(在Obj之后)定义Test。

The following works fine: 以下工作正常:

#include <iostream>
#include <cstring>
using namespace std;

class Obj {
public:
    static void print()
    {
        cout << "print here" << endl;
    }
};

class Test {
public:
    Test()
    {

    }
    ~Test()
    {

    }
    void foo()
    {
            Obj::print();
    }
};

int main()
{
    Test test;
    test.foo();
    return 0;
}

However it is always nicer (in my opinion) to separate declaration from definition for all but the most trivial of cases. 但是(在我看来)将除最琐碎的情况之外的所有情况的声明与定义分开总是更好的选择。

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

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