c++ - 将结构传递给函数

标签 c++ struct

我无法理解如何将结构(通过引用)传递给函数,以便可以填充结构的成员函数。到目前为止,我已经写了:

bool data(struct *sampleData)
{

}

int main(int argc, char *argv[]) {

      struct sampleData {
    
        int N;
        int M;
        string sample_name;
        string speaker;
     };
         data(sampleData);

}

我得到的错误是:

C++ requires a type specifier for all declarations bool data(const &testStruct)

我已经尝试过这里解释的一些示例:Simple way to pass temporary struct by value in C++?

希望有人可以帮助我。

最佳答案

首先,你的 data() 函数的签名:

bool data(struct *sampleData)

不可能工作,因为参数缺少名称。当您声明要实际访问的函数参数时,它需要一个名称。所以把它改成这样:

bool data(struct sampleData *samples)

但在 C++ 中,您实际上根本不需要使用 struct。所以这可以简单地变成:

bool data(sampleData *samples)

其次,此时 data() 不知道 sampleData 结构。所以你应该在此之前声明它:

struct sampleData {
    int N;
    int M;
    string sample_name;
    string speaker;
};

bool data(sampleData *samples)
{
    samples->N = 10;
    samples->M = 20;
    // etc.
}

最后,您需要创建一个 sampleData 类型的变量。例如,在您的 main() 函数中:

int main(int argc, char *argv[]) {
    sampleData samples;
    data(&samples);
}

请注意,您需要将变量的地址传递给 data() 函数,因为它接受一个指针。

但是,请注意,在 C++ 中,您可以通过引用直接传递参数,而无需使用指针“模拟”它。你可以这样做:

// Note that the argument is taken by reference (the "&" in front
// of the argument name.)
bool data(sampleData &samples)
{
    samples.N = 10;
    samples.M = 20;
    // etc.
}

int main(int argc, char *argv[]) {
    sampleData samples;

    // No need to pass a pointer here, since data() takes the
    // passed argument by reference.
    data(samples);
}

关于c++ - 将结构传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15181765/

相关文章:

c++ - C++ 将文件中的数据读入多个数组

c++ - C++23中省略参数列表的lambda表达式的有效性

c++ - 如何将项目添加到 MFC 对话框中的列表控件

c++ - C++ 中的 GUID 常量(在特定的 Orwell Dev-C++ 中)

serialization - 结构体到磁盘的高效 Go 序列化

c - 使用宏初始化结构

c++ - 我可以 typedef 模板模板参数吗?

c++ - 全局结构是分配在栈上还是堆上?

c - 预处理器宏解释?

c - 程序多次接受最后一行