为什么无法创建空类的const对象

时间:2011-03-17 06:55:54

标签: c++ const empty-class

#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();
}

上面的代码无法编译,有人可以告诉我为什么吗?

2 个答案:

答案 0 :(得分:13)

您需要初始化它。 This is a known problem with the spec

答案 1 :(得分:4)

将其初始化为:

const A ac = A();

工作代码:http://www.ideone.com/SYPO9


顺便说一句,这是初始化:const A ac(); //deceptive - not an initializaiton!