在 c++ 中访问 getter setter 内部的结构变量班级
好的,我在 C++ 中有类似的东西:
class MyClass{
private:
int someVariable;
int someOtherVariable;
struct structName{
int someStructVariable;
int someOtherStructVariable;
};//end of struct
public:
//getters & setters for the defined variables.
int getSomeStructVariable()
{
// this does not work I get this error: "error: expected primary-expression
// before '.' token"
return structName.someStructVariable;
}
};//end of class
在这种情况下我应该如何编写我的 getter 或 setter?
Okay, I have something like this in C++:
class MyClass{
private:
int someVariable;
int someOtherVariable;
struct structName{
int someStructVariable;
int someOtherStructVariable;
};//end of struct
public:
//getters & setters for the defined variables.
int getSomeStructVariable()
{
// this does not work I get this error: "error: expected primary-expression
// before '.' token"
return structName.someStructVariable;
}
};//end of class
How should I write my getter or setter in this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
structName
是类型名称的一部分,而不是变量名称的一部分。您需要给它一个名称,例如:然后在您的访问器中使用:
这应该会得到您想要的结果。结构变量的其他替代方法是将结构定义与变量声明分开:
或者添加到
typedef
中:structName
is part of the type name, not the variable name. You need to give it a name, something like:And then in your accessor use:
That should get you the result you want. Other alternatives for the structure variable are to separate out the structure definition from the variable declaration:
or to add in
typedef
:这是一个完整的例子。如果您想要一个镜像
set_n
而不是操纵数据的东西,那么您可能应该删除 getter/setter(因为您会错误地使用它们)并将数据成员公开。另外,请记住:使用
struct
定义类与使用class
定义类的工作方式相同,但有一个例外:public 而不是 private 作为默认访问权限成员和基地。Here's a complete example. If you want a mirror
set_n
instead of something which manipulates the data, then you should probably drop the getter/setter (as you'd be using them incorrectly) and make the data member public.Also, remember: defining classes with
struct
works identically to defining classes withclass
but for one exception: public instead of private as the default access for members and bases.为每个结构体字段编写 getter/setter 并不是一个好主意。更好的解决方案是:
将
structType
和MyClass
分开。将 getter 用作:需要第一个
const
来返回 const 值。第二个是 const- Correctness 所必需的。有两种方法可以定义 setter:
使用第一种方法:
第二个版本还允许您修改单独的结构字段:
请注意,如果结构包含指针,则 setter 可能需要一些调整。
It is not a good idea to write a getter/setter for each structure field. A better solution is:
Keep
structType
andMyClass
separate. Use the getter as:The first
const
is needed to return a const value. The second one is needed for const-correctness.There are two ways to define a setter:
Use the first one as:
The second version enables you to modify separate structure fields as well:
Note that the setter might need some adjustments if the structure contains pointers.