Code Monkey home page Code Monkey logo

chenhai813.github.io's People

Contributors

chenhai813 avatar

Watchers

 avatar  avatar

chenhai813.github.io's Issues

C++的初步使用【从结构体到类】

从结构体到类

【结构体的定义和使用】

#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
 */

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.