为什么我们不能在 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 或更高版本中执行此操作。如果您需要使用当前版本本身,您应该使用构造函数(希望您知道构造函数是什么,如果不只是 google 它)
你的代码应该是这样的
struct tester
{
int pt;
int bt;
tester() : bt(25) // Initializer list
} one;
或者
struct tester
{
int pt;
int bt;
tester()
{
bt=25;
}
} one;
你可以在 C++11 中。您只需在 gcc 或 clang 中启用编译选项,在 MSVC 2012+ 中它默认启用。
struct tester
{
int pt{0};
int bt{25};
} one;
如果你必须坚持使用旧的 C++,那么你需要一个构造函数作为
在其他回复中显示
尽可能使用初始化列表。
初始化器列表为对象选择最匹配的构造函数,这与赋值有根本区别。
#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
}
struct tester
{
int pt;
int bt=25; <--- this lines gives an error why ?
} one;
您实际上可以在 c++11 或更高版本中执行此操作。如果您需要使用当前版本本身,您应该使用构造函数(希望您知道构造函数是什么,如果不只是 google 它)
你的代码应该是这样的
struct tester
{
int pt;
int bt;
tester() : bt(25) // Initializer list
} one;
或者
struct tester
{
int pt;
int bt;
tester()
{
bt=25;
}
} one;
你可以在 C++11 中。您只需在 gcc 或 clang 中启用编译选项,在 MSVC 2012+ 中它默认启用。
struct tester
{
int pt{0};
int bt{25};
} one;
如果你必须坚持使用旧的 C++,那么你需要一个构造函数作为 在其他回复中显示
尽可能使用初始化列表。
初始化器列表为对象选择最匹配的构造函数,这与赋值有根本区别。
#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
}