#include<iostream>structPoint3d{doublex{0.0};doubley{0.0};doublez{0.0};};Point3dgetZeroPoint(){// We can create a variable and return the variable (we'll improve this below)Point3dtemp{0.0,0.0,0.0};returntemp;}intmain(){Point3dzero{getZeroPoint()};if(zero.x==0.0&&zero.y==0.0&&zero.z==0.0)std::cout<<"The point is zero\n";elsestd::cout<<"The point is not zero\n";return0;}
在函数有显式返回类型的情况下(例如: Point3d )而不是使用类型演绎(一个 auto 返回类型),我们甚至可以在return语句中省略类型:
123456
Point3dgetZeroPoint(){// We already specified the type at the function declaration// so we don't need to do so here againreturn{0.0,0.0,0.0};// return an unnamed Point3d}
Point3dgetZeroPoint(){// We can use empty curly braces to value-initialize all membersreturn{};}
包含程序自定义类型成员的结构体
在C++中,结构体(和类)的成员可以是其他程序定义的类型。有两种方法可以做到这一点。
首先,可以定义一个程序定义类型(在全局作用域),然后将其作为另一个程序定义类型的成员:
1 2 3 4 5 6 7 8 91011121314151617181920
#include<iostream>structEmployee{intid{};intage{};doublewage{};};structCompany{intnumberOfEmployees{};EmployeeCEO{};// Employee is a struct within the Company struct};intmain(){CompanymyCompany{7,{1,32,55000.0}};// Nested initialization list to initialize Employeestd::cout<<myCompany.CEO.wage;// print the CEO's wage}
在上面的例子中,我们首先定义了一个 Employee 结构体,然后将其作为另一个 Company 结构体的成员。 当 Company 初始化时,也可以通过嵌套的初始化值列表初始化Employee。如果我们想知道某个CEO的薪水是多少,则需要使用两次成员选择运算符:myCompany.CEO.wage;
其次,类型也可以被嵌套定义在其他类型中,搜易如果 Employee 只会作为 Company 的成员使用,则可以将其定义在 Company 结构体中:
1 2 3 4 5 6 7 8 91011121314151617181920
#include<iostream>structCompany{structEmployee// accessed via Company::Employee{intid{};intage{};doublewage{};};intnumberOfEmployees{};EmployeeCEO{};// Employee is a struct within the Company struct};intmain(){CompanymyCompany{7,{1,32,55000.0}};// Nested initialization list to initialize Employeestd::cout<<myCompany.CEO.wage;// print the CEO's wage}
#include<iostream>structFoo1{shorta{};shortqq{};// note: qq is defined hereintb{};doublec{};};structFoo2{shorta{};intb{};doublec{};shortqq{};// note: qq is defined here};intmain(){std::cout<<"The size of Foo1 is "<<sizeof(Foo1)<<'\n';std::cout<<"The size of Foo2 is "<<sizeof(Foo2)<<'\n';return0;}