相关疑难解决方法(0)

为什么C++需要用户提供的默认构造函数来默认构造一个const对象?

C++标准(第8.5节)说:

如果程序要求对const限定类型T的对象进行默认初始化,则T应为具有用户提供的默认构造函数的类类型.

为什么?在这种情况下,我无法想到为什么需要用户提供的构造函数.

struct B{
  B():x(42){}
  int doSomeStuff() const{return x;}
  int x;
};

struct A{
  A(){}//other than "because the standard says so", why is this line required?

  B b;//not required for this example, just to illustrate
      //how this situation isn't totally useless
};

int main(){
  const A a;
}
Run Code Online (Sandbox Code Playgroud)

c++

96
推荐指数
3
解决办法
2万
查看次数

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

#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();
}
Run Code Online (Sandbox Code Playgroud)

上面的代码无法编译,你能不能告诉我为什么?

c++ const empty-class

11
推荐指数
1
解决办法
572
查看次数

const 对象的编译器投诉未初始化

可能重复:
未初始化的常量

我知道需要初始化 const 对象。

所以对于下面的代码,

class sample
{};

int main()
{
   const sample obj;
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器会抱怨,因为 const 对象obj没有初始化。

但是当我使用默认构造函数修改代码(如下所示)时,编译器不会抛出任何错误。

class sample
{
    public:
       sample() { }
};

int main()
{
    const sample obj;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

新添加的默认ctor做了哪些让编译器满意的事情?

c++ constructor constants default-constructor

4
推荐指数
1
解决办法
1038
查看次数

为什么gcc不能编译未初始化的全局const?

当我尝试使用g ++编译以下内容时:

const int zero;

int main()
{
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我得到一个错误uninitialized const 'zero'.我认为全局变量默认初始化为0 [1]?为什么不是这种情况?
VS编译这个罚款.

[1]例如,请参阅/sf/answers/764910541/

gcc g++ global-variables

3
推荐指数
1
解决办法
2653
查看次数