但我的代码中没有此标记(' - ')。我所做的就是尝试分配colors
枚举类类型的变量,在每种情况下都是colors
的可能值之一,并且我收到此错误:< / p>
error: expected primary-expression before '-' token
在每个案例陈述的每个第一个陈述中。有人可以解释这个错误以及它为什么会发生吗?
完整代码:
源文件
#include "Bunny.h"
#include <cstdlib>
#include <time.h>
#include <string>
#include <iostream>
using namespace std;
Bunny::Bunny() : radioactive_mutant_vampire_bunny(false), age(0)
{
srand(time(NULL));
if(rand()%100 + 1 <= 2)
radioactive_mutant_vampire_bunny = true;
switch(rand()%4 + 1){
case 1:
color = colors.WHITE;
break;
case 2:
color = colors.BROWN;
break;
case 3:
color = colors.BLACK;
break;
case 4:
color = colors.SPOTTED;
break;
default:
cout << "The number entered is outside the range of 1 to 4.";
break;
}
name = names[rand()%names.size()];
}
Bunny::~Bunny()
{
//dtor
}
标题
#ifndef BUNNY_H
#define BUNNY_H
#include <string>
using namespace std;
class Bunny
{
public:
Bunny();
virtual ~Bunny();
protected:
private:
enum class sex{MALE, FEMALE};
sex sex;
enum class colors{WHITE, BROWN, BLACK, SPOTTED};
colors color;
int age;
string names[6] = {"Berry", "Jerry", "Terry", "Marie", "Perry", "Kerry"};
string name;
bool radioactive_mutant_vampire_bunny;
};
#endif // BUNNY_H
答案 0 :(得分:1)
colors.WHITE
是Java风格。在C ++中,您应该写为colors::WHITE
。names.size()
无效,因为names
不是类,而是数组。试试这个:
Bunny::Bunny() : radioactive_mutant_vampire_bunny(false), age(0)
{
srand(time(NULL));
if(rand()%100 + 1 <= 2)
radioactive_mutant_vampire_bunny = true;
switch(rand()%4 + 1){
case 1:
color = colors::WHITE;
break;
case 2:
color = colors::BROWN;
break;
case 3:
color = colors::BLACK;
break;
case 4:
color = colors::SPOTTED;
break;
default:
cout << "The number entered is outside the range of 1 to 4.";
break;
}
name = names[rand()%(sizeof(names)/sizeof(*names))];
}
答案 1 :(得分:1)
Sys.info()
sysname release version nodename
"Windows" "7 x64" "build 7601, Service Pack 1" "thepc"
machine login user effective_user
"x86-64" "theuser" "R version 3.2.5 (2016-04-14)" "theuser" "theuser"
enum class sex{MALE, FEMALE};
sex sex;
的名称为enum class
,您无法再次使用sex
,重命名您的会员:sex
sex _sex;
这不是case 1:
color = colors.WHITE;
break;
case 2:
color = colors.BROWN;
break;
case 3:
color = colors.BLACK;
break;
case 4:
color = colors.SPOTTED;
break;
的工作方式。使用enum classes
运算符代替::
运算符。
您的.
数组是普通的C数组,普通数组没有strings
方法,可以将其设为size()
或使用vector
用于检查数组长度的习语。