#include<iostream>structEmployee{intid{};intage{};doublewage{};};intmain(){Employeejoe{1,34,65000.0};// Use member selection operator (.) to select a member from struct object++joe.age;// Joe had a birthdayjoe.wage=68000.0;// Joe got a promotionreturn0;}
#include<iostream>structEmployee{intid{};intage{};doublewage{};};voidprintEmployee(constEmployee&e){// Use member selection opeartor (.) to select member from reference to structstd::cout<<"Id: "<<e.id<<'\n';std::cout<<" Age: "<<e.age<<'\n';std::cout<<" Wage: "<<e.wage<<'\n';}intmain(){Employeejoe{1,34,65000.0};++joe.age;joe.wage=68000.0;printEmployee(joe);return0;}
结构体指针的成员选择
不过,成员选择运算符并不能被用于指向结构体的指针:
1 2 3 4 5 6 7 8 9101112131415161718192021
#include<iostream>structEmployee{intid{};intage{};doublewage{};};intmain(){Employeejoe{1,34,65000.0};++joe.age;joe.wage=68000.0;Employee*ptr{&joe};std::cout<<ptr.id<<'\n';// Compile error: can't use operator. with pointersreturn0;}
#include<iostream>structEmployee{intid{};intage{};doublewage{};};intmain(){Employeejoe{1,34,65000.0};++joe.age;joe.wage=68000.0;Employee*ptr{&joe};std::cout<<(*ptr).id<<'\n';// Not great but works: First dereference ptr, then use member selectionreturn0;}
#include<iostream>structEmployee{intid{};intage{};doublewage{};};intmain(){Employeejoe{1,34,65000.0};++joe.age;joe.wage=68000.0;Employee*ptr{&joe};std::cout<<ptr->id<<'\n';// Better: use -> to select member from pointer to objectreturn0;}
#include<iostream>#include<string>structPaw{intclaws{};};structAnimal{std::stringname{};Pawpaw{};};intmain(){Animalpuma{"Puma",{5}};Animal*ptr{&puma};// ptr is a pointer, use ->// paw is not a pointer, use .std::cout<<(ptr->paw).claws<<'\n';return0;}
注意 (ptr->paw).claws中的括号是可选的,因为 operator-> and operator. 都是从左向右进行运算的,但是添加括号可以提高可读性。