为什么我们不能在 Struct C++ 中使用硬编码或初始化值?

Why can't we use hard coded or initialize a value in Struct C++?

本文关键字:编码 初始化 不能 我们 Struct C++ 为什么      更新时间:2023-10-16
struct tester 
{
    int pt;
    int bt=25;  <--- this lines gives an error why ?
} one;

您可以在C++11中使用。你只需要在gcc或clang中启用编译选项,在MSVC 2012+中,它是默认启用的。

struct tester 
{
    int pt{0};
    int bt{25}; 
} one;

如果你必须使用旧的C++,那么你需要一个构造函数显示在其他回复中

您实际上可以在c++11或更高版本中做到这一点。如果你需要使用当前版本本身,你应该使用构造函数(希望你知道什么是构造函数,如果不是谷歌它)

这就是你的代码应该看起来像的样子

struct tester 
{
    int pt;
    int bt;
    tester() : bt(25)   // Initializer list
} one;

或者

struct tester 
{
    int pt;
    int bt;
    tester()
      {
          bt=25;
      }
} one;

尽可能多地使用初始值设定项列表。

Initializer列表为对象选择最匹配的构造函数,这与赋值有根本不同。

#include<valarray>
    struct tester 
    {
        std::valarray<int> pt;
        const std::valarray<int> bt;
        tester() : pt(25) // Initialize pt to an valarray with space for
                          // 25 elements, whose values are uninitialized.
                          // Works well but may be confusing to most 
                          // people.
                  , bt(0, 25)   // initialize bt to an valarray of 25 zeros
    }