I want to create functions with dot operator like these:
Regedit.Key.Create();
Regedit.Value.Create();
Regedit.Value.Read();
How can I do that?
CodePudding user response:
In C you will need to write getter functions, and then the syntax becomes editor.Key().Create();
class Key
{
public:
Key() = default;
~Key() = default;
void Create()
{
};
};
class RegEdit
{
public:
// in C you need to use a getter function
Key& key()
{
return m_key;
}
private:
Key m_key;
};
int main()
{
RegEdit editor;
editor.key().Create();
return 0;
}
CodePudding user response:
For Regedit.Key.Create();
to be a valid C instruction, some conditions are required:
Regedit
must be an object (ie an instance of a C class)Key
must be a member attribute ofRegedit
- that attribute must also be an object
Create
must be a method of that object
Here is an example code meeting those conditions, where RegAccessor
is the class for Regedit
and Selector
is the class for Regedit.Key
:
#include <iostream>
class Selector {
public:
enum class Type {
Key,
Value
};
friend std::ostream& operator << (std::ostream& out, const Type& type) {
const char *name;
switch (type) {
case Type::Key: name = "Key"; break;
case Type::Value: name="Value"; break;
default: name="Unknown";
}
out << name;
return out;
}
Selector(Type type): type(type) {};
void Create() {
// write more relevant code here...
std::cout << "Create " << type << " called\n";
}
void Read() {
// write more relevant code here...
std::cout << "Read " << type << " called\n";
}
private:
Type type;
};
class RegAccessor {
public:
Selector Key = Selector::Type::Key;
Selector Value = Selector::Type::Value;
};
int main(int argc, char **argv)
{
RegAccessor Regedit;
// here is exactly your example code
Regedit.Key.Create();
Regedit.Value.Create();
Regedit.Value.Read();
return 0;
}