C++ 使用类作为变量

标签 c++ class variables operator-overloading operators

所以我有一个类似于这个的类:

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....

关于C++ 使用类作为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31143642/

相关文章:

每个派生类的 C++ 分离静态字段

c++ - 应用程序退出时线程无法退出 - C++

javascript - 使用 MooTools 使 Javascript 变量成为全局变量

c++ - 如何将对象 C1 设置为输入半径?

javascript - 是否可以将 JS 变量连接到 PHP 邮件方法中,如果可以,如何实现?

c++ - 用于 C/C++ 编程的好的 gvim guifont 是什么

c++ - c++中数组的动态内存分配

c++ - 将正符号变量替换为无符号变量

javascript - Typescript - 在不实现接口(interface)父级的情况下实现接口(interface)

java存储实例变量并使用键值之一进行访问