C++ 使用 Class 作为变量
C++ Use Class as Variable
所以我有一个 class 类似于这个:
class CVal {
public:
void operator=(int n) {
d = n;
}
private:
int d;
};
现在每当我做类似的事情时
CVal c;
switch(c) {...}
我想要 CVal::d 被访问,那么我该怎么做呢?我想重载一些运算符,但我找不到任何东西。
你应该这样定义转换运算符
class CVal {
public:
//...
operator int() const { return d; }
private:
int d;
};
或者,如果你有一个支持 C++ 2014 的编译器,那么你可以按以下方式定义它
class CVal {
public:
//...
operator auto() const { return d; }
private:
int d;
};
根据C++标准(6.4.2 switch语句)
2 The condition shall be of integral type, enumeration type, or class
type. If of class type, the condition is contextually implicitly
converted (Clause 4) to an integral or enumeration type. Integral
promotions are performed....
您不能访问class的私有成员。但是如果你想无论如何都使用私有成员的值,你需要编写 get 函数。例如:
class CVal {
public:
void operator=(int n) {
d = n;
}
int getD() { // this function returns the value of private member d
return d;
}
private:
int d;
};
现在您可以通过以下方式访问d:
CVal c;
switch(c.getD()) {...}
此选项优于隐式转换 class 以使其可在 switch 中访问。因为它可以避免您将来可能出现的调试错误。此外,许多编码约定更喜欢此选项。
所以我有一个 class 类似于这个:
class CVal {
public:
void operator=(int n) {
d = n;
}
private:
int d;
};
现在每当我做类似的事情时
CVal c;
switch(c) {...}
我想要 CVal::d 被访问,那么我该怎么做呢?我想重载一些运算符,但我找不到任何东西。
你应该这样定义转换运算符
class CVal {
public:
//...
operator int() const { return d; }
private:
int d;
};
或者,如果你有一个支持 C++ 2014 的编译器,那么你可以按以下方式定义它
class CVal {
public:
//...
operator auto() const { return d; }
private:
int d;
};
根据C++标准(6.4.2 switch语句)
2 The condition shall be of integral type, enumeration type, or class type. If of class type, the condition is contextually implicitly converted (Clause 4) to an integral or enumeration type. Integral promotions are performed....
您不能访问class的私有成员。但是如果你想无论如何都使用私有成员的值,你需要编写 get 函数。例如:
class CVal {
public:
void operator=(int n) {
d = n;
}
int getD() { // this function returns the value of private member d
return d;
}
private:
int d;
};
现在您可以通过以下方式访问d:
CVal c;
switch(c.getD()) {...}
此选项优于隐式转换 class 以使其可在 switch 中访问。因为它可以避免您将来可能出现的调试错误。此外,许多编码约定更喜欢此选项。