首页 > 解决方案 > 在main中增加类的静态成员 - C++

问题描述

我收到此错误error: expected unqualified-id before ‘++’ token 29 | std::cout<<x::foo::++z;

基本上我正在尝试z从 main 中的 foo递增

#include <iostream>

namespace x {
  class foo {
  public:
    void bar1(foo& f) {
      ++x;     
    }
    friend void bar2(foo& f);

    int x;
    int y;
    static  int z;
  };

  int x::foo::z=15;
  void bar2(foo& f) {
    f.y++;       // Error: y not in scope
  }
}

int main() {
  x::foo a;
  ++a.x=5;
  std::cout << ++a.x << std::endl;
  std::cout << x::foo::z;
  std::cout << x::foo::++z; //throws error
  return 0;
}

z 是静态成员。

我的问题是如何访问和增加静态成员z?也可以在 C++ 中的类之外完成声明,不知何故?

标签: c++

解决方案


您必须首先指定操作++运算符),然后指定要调用运算符的对象x::foo::z( ):

// Increment the x::foo::z
++x::foo::z; 
// Equivalent to ++(x::foo::z)

推荐阅读