why a const object of an empty class cant be created

删除回忆录丶 提交于 2019-12-08 16:39:01

问题


#include <iostream>

class A {
   public:
      void foo() const {
          std::cout << "const version of foo" << std::endl;
      }
      void foo() {
          std::cout << "none const version of foo" << std::endl;
      }
};

int main()
{
  A a;
  const A ac;
  a.foo();
  ac.foo();
}

The above code can't be compiled, could anyone of you tell me why?


回答1:


You need to initialize it. This is a known problem with the spec.




回答2:


Initialize it as:

const A ac = A();

Working code : http://www.ideone.com/SYPO9


BTW, this is not initializaiton : const A ac(); //deceptive - not an initializaiton!



来源:https://stackoverflow.com/questions/5335836/why-a-const-object-of-an-empty-class-cant-be-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!