用不同值进行比较的c++ int包装器类不起作用

C++ int wrapper class with different values for comparison not working

本文关键字:int c++ 包装 不起作用 比较      更新时间:2023-10-16

为什么下面的用法给我一个错误:所以下面是我的测试用例和类就在它下面,头和cpp:测试:

Environment bla;
bla=Environment::CTE;
if(bla==1){
    printf("CTE!");
}else if(bla==Environment::PPE){
    printf("NO: its ppe");
}
头:

class Environment{
public:
enum{CTE, PTE, PPE, LOCALHOST};
static int self;
bool operator==(const int& rhs)const;
Environment& operator=(const int &rhs);
};

和CPP:

#include "Environment.h"
bool Environment::operator==(const int& rhs)const{
if (this->self ==rhs)
    return true;
return false;
}
Environment& Environment::operator=(const int &rhs) {
  if (this->self != rhs) {
  this->self=rhs;
}
  return *this;
}

您已将self声明为static。这意味着:

  1. 你必须在某处定义它。也就是说,将int Environment::self;放入一个.cpp文件中。

  2. 作为static意味着整个类只有一个self实例。因此,通过this->self访问它是不必要的,实际上是令人困惑的。这似乎意味着类Environment的每个实例都有自己的副本,但事实并非如此。

如果希望Enviornment的每个实例都有自己的self值,只需从self的声明中删除static关键字。