gpt4 book ai didi

c++ - 在类中构建结构

转载 作者:太空宇宙 更新时间:2023-11-03 10:30:51 25 4
gpt4 key购买 nike

我正在迈出学习 OOP 的第一步。这是我无法解决的第一个问题。此类中的 max 函数应返回两个数字中的最大值。我想将数字保留在私有(private)范围内,将功能保留在公共(public)范围内。但是,当我想在公共(public)范围内使用 struct data{} 中的变量时,编译器会提示未声明变量。请告诉我为什么会出现这些错误。

class myclass{
private:
struct data{
int q ;
int w;
};

public:
void get(int a, int b){
struct data = {a , b}; // here I want to pass the variables to data struct
}
int max (){ // this function returns the biggest number
if(q>w)
return q;
else
return w;
}

};

最佳答案

struct data{
int q ;
int w;
};

只声明一个类型,而不是一个对象,所以里面的任何地方都没有qw成员你的 class 实例。您需要声明 struct实例:

struct {
int q;
int w;
} data;

然后,你可以将max写成:

int max()
{
if (data.q > data.w)
return data.q;
else
return data.w;
}

(我不知道您的 get 方法应该做什么,所以我没有替代方法。)

关于c++ - 在类中构建结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17254095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com