banner
cells

cells

为美好的世界献上 code

Q264

Q264#

#include <iostream>

struct C {
    C() = default;
    int i;
};

int main() {
    const C c;
    std::cout << c.i;
}

Explain#

This is not allowed since it is const and C has a defaulted (not user-provided) constructor.

There are several ways we could make C const-default-constructible:

  • Give int i a default member initializer: int i {0}.
  • Remove = default from the constructor, and instead do C::C() = default; separately outside the class definition. This constructor now counts as user-provided.
  • Manually provide a constructor: C() {}.

Answer#

click to see answer The program has a compilation error
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.