为什么我得到表达式必须有类类型错误?

Why am I getting expression must have class type error?

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

我试图运行这个简单的代码块,但出现错误:表达式必须具有tom.nametom.id的类类型。我在这里做错了什么?

#include <iostream>
#include <string>
using namespace std;
class Student
{
string name;
int id;
int age;
};

int main()
{
Student* tom = new Student;
tom.name = "tom";
tom.id = 1;
}

您访问指针不正确。从指针访问内部变量需要->而不是.运算符。

切换您的代码:

Student* student_ptr = new Student;
student_ptr->name = "Tom";
student_ptr->id = 1;

或者,如果您确实想使用.运算符,您可以执行以下操作:

Student* student_ptr = new Student;
(*student_ptr).name = "Tom";
(*student_ptr).id = 1; // the more you know