错误:表达式必须具有类类型

error: expression must have class type

本文关键字:类型 表达式 错误      更新时间:2023-10-16

首先,我知道还有其他问题与本问题基本相同,但似乎没有一个答案对我有效。我对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>

当然,在下一行中为函数调用添加括号。

相关文章: