相关疑难解决方法(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万
查看次数

为什么成员`float x`用`0`初始化为main()中的对象`a`和`b`?

有人可以指出标准中的哪个子句支持在Coliru中获得的以下行为,对于该片段:

#include <iostream>

class A
{
    int i;
    float x;

    public:
    A() : i(10) {}
    A(int i) : i(i) {}
    int GetI() { return i; }
    float GetF() { return x; }
};


int main()
{
    A a;
    A b(1);
    A x{};
    A y{1};
    std::cout << a.GetI() << '\n';
    std::cout << a.GetF() << '\n';
    std::cout << b.GetI() << '\n';
    std::cout << b.GetF() << '\n';
    std::cout << x.GetI() << '\n';
    std::cout << x.GetF() << '\n';
    std::cout << y.GetI() << '\n';
    std::cout …
Run Code Online (Sandbox Code Playgroud)

c++ default-constructor c++11

9
推荐指数
1
解决办法
333
查看次数

标签 统计

c++ ×2

c++11 ×1

default-constructor ×1