将struct参数传递给struct中的函数

时间:2016-08-05 22:39:52

标签: c++ pointers struct reference

我目前面临C ++中的结构问题。按照下面的代码,然后我可以解释问题。

void TestFunction(testStructure *tempStructValue)
{

     cout << tempStructValue->data << endl;

     return &tempStructValue->data;

}

typedef struct testStructure

{

    int data;

    void *TestFunction(testStructure *tempStructValue)

}temp;

该函数在struct之前定义。这样,函数有一个参数作为结构,但结构是在函数定义之后定义的。这显然是一个错误。

现在,反思一下。在函数之前定义结构。执行此操作仍会抛出错误,因为函数将在稍后的代码中定义,结构将搜索该函数。

这种鸡和鸡蛋问题有解决方案吗?

2 个答案:

答案 0 :(得分:0)

如果是c代码。将文件分成3个文件可以解决问题。为struct创建一个头文件,为函数创建一个头文件可能是解决方案。在struct文件中包含函数heder。然后在函数的c文件中包含struct heder。 但是如果你的代码是用c ++编写的(cout让我觉得它更有可能)你应该尝试一些OOA,OOD,并且可能是满足你需求的解决方案的设计模式技术。

同时函数的返回值必须是指针类型。

答案 1 :(得分:0)

你可以“转发声明”一个类,以便它可以在它的完整定义之前由指针或引用引用。

class MyClass;  // forward declaration

void fn1(MyClass* ptr);  // legal

void fn2(MyClass* ptr)  // legal
{
    ptr->something;  // illegal, definition of MyClass unknown
}

class A {
    MyClass mc;  // illegal, definition of MyClass unknown
};

class MyClass {
    // ...
};

但是,在您的示例中,您编写了以下内容:

typedef struct testStructure
{
    int data;
    void *TestFunction(testStructure *tempStructValue)
} temp;

这声明了一个类testStructure,它作为整数成员data成员函数 TestFunction返回void*指针。此成员函数与之前的自由函数TestFunction完全没有关联。目前还不清楚你的意图是什么。

示例:

#include <iostream>

struct TestStructure;

void TestFunction(TestStructure* /*unused*/) {
    std::cout << "Free TestFunction\n";
}

struct TestStructure {
    int i;
    void TestFunction(TestStructure* /*unused*/) {
        std::cout << "TestStructure TestFunction\n";
    }
    void foo() {
        std::cout << "From foo\n";
        TestFunction(this);
    }
};

int main() {
    std::cout << "From main:\n";
    TestFunction(nullptr);

    TestStructure t;
    t.foo();
}

http://ideone.com/1453GG

如果以相反的方式宣布它们,情况也是如此:http://ideone.com/VDcJxe

这是因为名称是根据范围解决的。在查找else之前,类/结构的成员函数将查询类/结构的自己的作用域。如果我们想从成员函数中调用自由函数,我们可以使用'::'范围运算符:

void foo() {
    ::TestFunction();  // resolves from the global scope
}

请参阅:http://ideone.com/B51J4C(注意我选择转发声明该函数,而该函数又要求我转发声明该类的参数)。

相关问题