我想用点运算符创建函数,如下所示:
Regedit.Key.Create();
Regedit.Value.Create();
Regedit.Value.Read();
我怎样才能做到这一点?
我想用点运算符创建函数,如下所示:
Regedit.Key.Create();
Regedit.Value.Create();
Regedit.Value.Read();
我怎样才能做到这一点?
在 C++ 中,您需要编写 getter 函数,然后语法变为 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;
}
要Regedit.Key.Create();
成为有效的 C++ 指令,需要一些条件:
Regedit
必须是对象(即 C++ 类的实例)Key
必须是的成员属性Regedit
Create
必须是该对象的方法这是一个满足这些条件的示例代码,其中RegAccessor
的类是Regedit
和Selector
的类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;
}