#include<iostream.h>
//
#include<iostream.h>等价于#include<iostream>+using namespace std
//using namespace std;
//struct Point
class Point
{
public: //类class中当访问标号缺省的情况下,成员默认为私有,不能被外部函数比如main()访问
//private: //类struct默认情况下为公有
//protected:
int x;
int y;
/* void init()
{
x=0;
y=0;
}*/
Point() //为保证唯一性,构造函数与类名一致,无返回值,可以有参数
//内存在构造函数分配
{
x=0;
y=0;
}
Point(int a,int b) //第二个含参的构造函数,这就叫构造函数的重载
//只有在“参数”的个数和类型不同时才叫重载
{
x=a;
y=b;
}
~Point() //析构函数最后执行,用来释放内存。不能带参数
{
}
void output() //c++中结构体中是可以包含函数的
{
cout<<x<<endl<<y<<endl;
}
void output(int x,int y)
{
this->x=x; //this是指向类的成员Pt的指针。(*this).x即pt.x
this->y=y;
}
/*void output(int x,int y)
{
x=x; //此重载output函数中的x,y相当与两个局部变量,
}*/
};
void main()
{
//pt.x=5;
//pt.y=5;
// pt.init();
pt.output(5,5);
pt.output();
// cout<<pt.x<<endl<<pt.y<<endl;
}
//using namespace std;
//struct Point
class Point
{
public: //类class中当访问标号缺省的情况下,成员默认为私有,不能被外部函数比如main()访问
//private: //类struct默认情况下为公有
//protected:
int x;
int y;
/* void init()
{
x=0;
y=0;
}*/
Point() //为保证唯一性,构造函数与类名一致,无返回值,可以有参数
//内存在构造函数分配
{
x=0;
y=0;
}
Point(int a,int b) //第二个含参的构造函数,这就叫构造函数的重载
//只有在“参数”的个数和类型不同时才叫重载
{
x=a;
y=b;
}
~Point() //析构函数最后执行,用来释放内存。不能带参数
{
}
void output() //c++中结构体中是可以包含函数的
{
cout<<x<<endl<<y<<endl;
}
void output(int x,int y)
{
this->x=x; //this是指向类的成员Pt的指针。(*this).x即pt.x
this->y=y;
}
/*void output(int x,int y)
{
x=x; //此重载output函数中的x,y相当与两个局部变量,
//巧合的是和成员变量同名,作用域的优先级高于成员变量,于是此函数的功能为形参的自我赋值
//由于和成员变量同名,于是系统自动把函数外面声明的x,y屏蔽了。函数内的x,y都是传入的参数,相当于把内存 中某个不知名的地址自己的值赋给了自己。而根本不会影响到类中的x,y值。
//所以不能复制给成员变量x,y。解决方法是:要么改掉形参名x,y,要么用this指针
y=y;}*/
};
void main()
{
Point pt(3,3); //会自动调用构造函数,而且根据参数类型自动匹配。此例匹配给含参的构造函数Point(int a, int b)
//(此时已经调用构造函数)
//pt.Point(3,3);这种写法错误。“构造函数会自动调用,但你没办法给它传递参数”//pt.x=5;
//pt.y=5;
// pt.init();
pt.output(5,5);
pt.output();
// cout<<pt.x<<endl<<pt.y<<endl;
}