如何修复表达式必须具有对象类型 C++

how to fix expression must have object type c++

本文关键字:对象 类型 C++ 何修复 表达式      更新时间:2023-10-16

我的编码或数据类型有问题。错误显示"表达式必须具有指向对象的指针类型"。我不知道如何解决这个问题。

#include <iostream>
#include <conio.h>
using namespace std;
int main() {
    int id, year, dates;
    cout << "Enter the ID number ";
    cin >> id;
    year = id[0] + id[1] + 1900;
    cout << year;
    getch();
    return 0;
}

拜托,有人知道你的解决方案吗?

您可以做一些简单的数学运算来访问 ID 的各个数字:

#include <iostream>
using namespace std;
int main(void)
{
    int id = 189;
    cout << id / 100 % 10 << endl;
    cout << id / 10 % 10 << endl;
    cout << id / 1 % 10 << endl;
    return 0;
}

耶尔兹:189

你的id是一个整数,但你把它当作一个数组使用:

id[0]+id[1]

您将id声明为 int ,但随后尝试在其上使用 [] 运算符。 编译器对此感到"困惑",并且正在尽最大努力弄清楚您在int上使用运算符的含义 - 它能做的最好的事情是告诉您表达式必须是指向对象的指针(换句话说,它告诉您它不能在 int 类型上使用运算符 - 而是指针或对象)。