预期 不允许使用表达式/类型名称

Expected An Expression / Type Name Not Allowed

本文关键字:类型 表达式 不允许 预期      更新时间:2023-10-16
Brixpath::Brixpath(){
{    _animationOptions = (AnimationOptions){5, 3, 40, 30}; 
};

当我运行此代码块时,VS给出错误

动画选项上不允许的类型名称。

当我删除类型名称时

Brixpath::Brixpath(){
{    _animationOptions = {5, 3, 40, 30}; 
};

VS2010 在第 2 行的第一个"{"处给出错误

错误:预期的表达式

动画选项的定义是-

struct AnimationOptions {
int maxClicks; //how many clicks animation on screen to support
int step; // animation speed, 3 pixels per time
int limit; //width of animation rectangle. if more, rectangle dissapears
int distance; //minimum distance between previous click and current
};

如何解决此错误?请帮忙。

给定VS 2010的用户(即不能使用C++11统一初始化(,您可能希望向结构中添加构造函数,然后使用它来初始化结构:

struct AnimationOptions {
    int maxClicks; //how many clicks animation on screen to support
    int step; // animation speed, 3 pixels per time
    int limit; //width of animation rectangle. if more, rectangle dissapears
    int distance; //minimum distance between previous click and current
    AnimationOptions(int maxClicks, int step, int limit, int distance) : 
        maxClicks(maxClicks), step(step), limit(limit), distance(distance) {}
};
Brixpath::Brixpath() : _animationOptions(5, 3, 40, 30) {}

如果您需要将动画选项维护为 POD,我相信您可以使用支撑初始化而不是成员初始化来简化代码:

AnimationOptions make_ao(int clicks, int step, int limit, int distance)
{
  AnimationOptions ao = {clicks, step, limit, distance};
  return ao;
};

这将起作用,并且是首选选项(需要 C++11(:

Brixpath::Brixpath() : _animationOptions{5, 3, 40, 30}
{
};

在这里,您在构造函数初始化列表中初始化_animationOptions,而不是在构造函数的主体中为其赋值。

在没有 C++11 支持的情况下,您可以AnimationOptions提供一个构造函数,在这种情况下它将不再是 POD,或者逐个元素设置。如果这是一个问题,您还可以创建一个初始值设定项函数:

AnimationOptions make_ao(int clicks, int step, int limit, int distance)
{
  AnimationOptions ao;
  ao.maxClicks = clicks;
  ao.step = step;
  ....
  return ao;
};

然后

Brixpath::Brixpath() : _animationOptions(make_ao(5, 3, 40, 30))
{
};

这会AnimationOptions保留为 POD,并将初始化与构造函数代码分离。

如何解决此错误?

使用 c++11 标准选项编译代码,或按成员方式初始化结构:

Brixpath::Brixpath()
{    
    _animationOptions.maxClicks = 5;
    _animationOptions.step = 3;
    _animationOptions.limit = 40
    _animationOptions.distance = 30; 
};
相关文章: