为什么我们不能在 Struct C++ 中使用硬编码或初始化值?
Why can't we use hard coded or initialize a value in Struct C++?
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
}
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 如何在类的初始值设定项列表中初始化 std::array,而不对数组的大小进行硬编码
- 错误:调用'begin(long double [nPoints])'没有匹配函数;使用硬编码的 int 与整数变量初始化向量
- 从相同的硬编码字符串文字初始化std::string和std::wstring
- 为不同平台初始化硬编码 int 的向量
- 为什么我们不能在 Struct C++ 中使用硬编码或初始化值?
- 初始化 utf8 编码字符串 c++11
- 使用硬编码元素初始化 std::vector 的最简单方法是什么<MyClass>?
- 用wmemset初始化wchar_t数组.编码重要吗?