[英]C ++, use a "typedef" of struct in a large "typedef" of struct
For my program I need to do something like this:对于我的程序,我需要执行以下操作:
myObject.objectFunction(Process.MARKING);
To do this I thought of doing it like this:为此,我想这样做:
file header:文件头:
typedef struct _process
{
string process_name;
string party_involved;
} process;
typedef struct _PROCESS
{
process MARKING;
MARKING.process_name = "...";
MARKING.party_involved = "...";
process COLORING;
COLORING.process_name = "...";
COLORING.party_involved = "...";
...
} PROCESS;
But I can't compile or correct the error.但我无法编译或更正错误。
I know I can use macros attached to namespaces, but I don't like having to use "::", and I also know that maybe this is not the best way to program.我知道我可以使用附加到命名空间的宏,但我不喜欢使用“::”,而且我也知道这可能不是最好的编程方式。
I forgot to add that I would also like to make the elements of the struct constant larger ie not editable after compile and I also need to use the typedef
of the smaller structure (process) outside the header file.我忘了补充一点,我还想让struct常量的元素更大,即编译后不可编辑,我还需要在头文件之外使用较小结构(进程)的
typedef
。
Can you tell me where I'm wrong, and/or a better way to do what I want to do?你能告诉我我错在哪里,和/或更好的方法来做我想做的事吗?
You actually don't need to typedef
your struct
s at all - they are type defined automatically.您实际上根本不需要
typedef
您的struct
s - 它们是自动定义的类型。 You do however have a problem with initializing.但是,您确实在初始化时遇到了问题。 In C++20, you can use designated initializers:
在 C++20 中,您可以使用指定的初始值设定项:
#include <string>
struct process {
std::string process_name;
std::string party_involved;
};
struct PROCESS {
process MARKING{
.process_name = "...",
.party_involved = "..."
};
// same for COLORING
};
And before C++20:在 C++20 之前:
struct process {
std::string process_name;
std::string party_involved;
};
struct PROCESS {
process MARKING{
"...",
"..."
};
// ...
};
If you don't want any other object to be allowed to make changes to these member variables, make them private
and provide const&
accessors:如果您不希望任何其他对象被允许对这些成员变量进行更改,请将它们设为
private
并提供const&
访问器:
struct PROCESS {
const process& getMarking() const { return MARKING; }
private:
process MARKING{
"...",
"..."
};
};
Now, myObject.objectFunction(Process.getMarking());
现在,
myObject.objectFunction(Process.getMarking());
can't change it and must either take the object by value or by const&
:无法更改它,必须通过值或
const&
获取对象:
struct Object{
void objectFunction(const process& MARKING) {
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.