chenhai813 / chenhai813.github.io Goto Github PK
View Code? Open in Web Editor NEW晨海的博客
晨海的博客
【结构体的定义和使用】
#include <iostream.h>
using namespace std;
struct point{ //定义结构体
int x; //定义成员变量
int y;
void print()//定义成员函数
{
cout<<"x="<<x<<endl; //输出成员变量的值
cout<<"y="<<y<<endl;
}
};
int main(void)
{
struct point pt; //定义结构体变量
pt.x = 0; //引用成员变量并赋值
pt.y = 1;
pt.print(); //引用成员函数
return 0;
}
/*
运行结果:
x=0
y=1
*/
【类的定义和使用】
class point{ //声明类
int x; //定义成员变量
int y;
void print()//定义成员函数
{
cout<<"x="<<x<<endl; //输出成员变量的值
cout<<"y="<<y<<endl;
}
};
int main(void)
{
point pt; //声明对象
pt.x = 0; //赋值
pt.y = 1;
pt.print(); //调用成员函数
return 0;
}
运行程序,却出现如下错误:
原因是,在默认情况下,结构体的成员是公有(public)的,类的成员是私有(private)的,这是结构体与类的区别之一
在一个类当中,公有成员是可以在类的外部进行访问的,而私有成员只能在类的内部进行访问,因此出现了上述不能访问私有成员的错误信息
接下来重新修改下代码,将类中定义的变量x和y,以及成员函数print()都定义为公有的,即在其上加标识符public
class point{ //声明类
public:
int x; //定义成员变量
int y;
void print()//定义成员函数
{
cout<<"x="<<x<<endl; //输出成员变量的值
cout<<"y="<<y<<endl;
}
};
int main(void)
{
point pt; //声明对象
pt.x = 0; //赋值
pt.y = 1;
pt.print(); //调用成员函数
return 0;
}
/*
运行结果:
x=0
y=1
*/
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.