错误:表达式必须具有类类型
error: expression must have class type
首先,我知道还有其他问题与本问题基本相同,但似乎没有一个答案对我有效。我对c++和编程很陌生,所以请尽可能简单地描述,谢谢。
因此,我试图制作一个简单的文本游戏,我有几个文件,但当我尝试使用类中的方法时,会导致一个错误,即表达式必须具有类类型。
这是代码。
main.cpp
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include "Warrior.h"
using namespace std;
//main function
int main (void)
{
//title screen
cout<< " _____ _ _ _____ n";
cout<< "| __|_|_____ ___| |___ | __ |___ ___ n";
cout<< "|__ | | | . | | -_| | -| . | . |n";
cout<< "|_____|_|_|_|_| _|_|___| |__|__| _|_ |n";
cout<< " |_| |_| |___|n";
cout<< "nn Enter any # to start n ";
int start;
anumber:
cin>> start;
if (start < 0 || start > 0)
{
cout<< "nWelcome to Sam Acker's simple rpg game!n";
}
Warrior your_warrior(int health , int armor , int weapon);
your_warrior.warrior_name_function; //This is the line with the error
int exit;
cin>> exit;
return 0;
}
Warrior.h
#include <string>
#include <iostream>
class Warrior
{
private:
int health;
int weapon;
int armor;
std::string warrior_name;
public:
int attack();
int warrior_name_function();
Warrior(int health , int weapon , int armor);
~Warrior();
};
Warrior.cpp
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include "Warrior.h"
int Warrior::warrior_name_function()
{
std::cout<< "What would you like to name you warrior?n";
std::cin>> Warrior::warrior_name;
return 0;
}
int Warrior::attack()
{
return 0;
}
Warrior::Warrior(int health , int armor , int weapon)
{
health == 100;
armor == 1;
weapon == 16;
}
Warrior::~Warrior()
{}
main()中的此行
Warrior your_warrior(int health , int armor , int weapon);
看起来您是在声明一个函数,而不是创建类Warrior
的实例。您应该用这样的变量的一些具体值来调用它,以创建一个
Warrior your_warrior(10,32,2);
或者更好地创建一些变量,设置它们的值并传递给函数。然后呼叫
your_warrior.warrior_name_function();
编译错误是因为它没有将你的warrior识别为类实例,而是将其识别为函数的声明。
调用name函数时似乎忘记了括号:
your_warrior.warrior_name_function();
我还建议您简单地删除Warrior
类的析构函数:它没有任何要清理的内容。
Warrior your_warrior(int health , int armor , int weapon);
这一行声明了一个函数named your_warrior
,该函数接受三个类型为int
的参数,并返回一个类型为Warrior
的对象。
如果去掉三个int
,效果会更好。<g>
当然,在下一行中为函数调用添加括号。
相关文章:
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 如何计算具有指定类型的表达式的相对精度和绝对精度
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 有没有办法一次声明相同类型的多个对象,并通过一个表达式立即使用相同的右值初始化它们?
- 表观调用前面的表达式必须具有指向 func 类型的指针
- 数组类型 int[n][n] 不可赋值,因为表达式必须具有常量值
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- C++ 编译错误:意外的类型名称"字符串":预期的表达式
- 表达式必须具有类类型 vs.
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 非类类型表达式的静态类型与动态类型之间的差异
- 如何确定涉及 C++ 中除法的算术表达式的数据类型
- 结构化绑定初始值设定项表单 { 赋值表达式 } 对于 clang 上的数组类型失败
- 下标需要数组或指针类型表达式必须具有指针对象类型
- 带有数组类型表达式的错误分配
- 表示函数参数的元组的类型表达式
- 如何确定撤销类型表达式的更大类型
- c++ 11中有新的函数类型表达式格式吗?