首页 > 解决方案 > C++ variable_name.attribute = x

问题描述

我看过这个,但我找不到他在做什么。我特别感兴趣computers[I].name = 'ever':你能在 C++ 中有一个 variable_name.attribute 吗?例如 student.grade = 6, student.name = "Tedd" 等等?

标签: c++arraysclassdictionaryvector

解决方案


当然,为什么不:

#include <string>

struct Computer {
  std::string name;
};

int main() {
  Computer computers[100];

  for (auto& cp : computers) {
    cp.name = "ever";
  }
}

这是您感兴趣的学生示例:

#include <string>
#include <iostream>

struct Student {
  std::string name;
  double grade;
};

int main() {
  Student students[3];
  students[0].name = "s1";
  students[0].grade = 95.7;

  students[1].name = "s2";
  students[1].grade = 96.6;

  students[2].name = "s3";
  students[2].grade = 77.4;

  for (Student const& s : students) {
    std::cout << s.name << " : " << s.grade << '\n';
  }
}

悬停执行

s1:95.7
s2:96.6
s3:77.4


推荐阅读