C++继承小程序出问题帮改下

来源:百度知道 编辑:UC知道 时间:2024/07/02 04:46:59
// point.h
#ifndef POINT_H
#define POINT_H

class point{
friend ostream &operator<< (ostream &,const point &);
public:
point(int = 0, int = 0);

void setpoint(int,int);
int getx() const {return x};
int gety() const {return y};

protected:
int x,y;
};

#endif
//point.cpp
#include "point.h"
#include <iostream>

using namespace std;

point::point(int n1, int n2)
{setpoint(n1,n2);}

void point::setpoint(int n1, int n2)
{
x = n1;
y = n2;
}

ostream &operator<<(ostream &output,const point &n)
{
output << "[ " << n.x << " " << n.y << " ]";

return output;
}
//main.cpp
#include <iostream>
#include "point.h"
#include <iomanip>

using namespace std;

i

1.分号放里面
int getx() const {return x;}
int gety() const {return y;}

2.#include <iostream>
using namespace std;

3.VC2003 能编译通过

1.分号放里面
int getx() const {return x;}
int gety() const {return y;}

2.在 point.h 的#ifndef POINT_H #define POINT_H 后面加上

#include <iostream>
using namespace std;
class point;
ostream &operator<< (ostream &,const point &);
这是前向声明,在类定义里的友元声明是不能代替函数声明的

你的X和Y都是保护类型成员,我不知道你完整程序是怎么样的,但是你写的n.x,n.y这样访问肯定是不允许的.不然你那个getx()和gety()就没有意义了

既然你用成员函数访问私有变量,那么肯定是要保证类的封装性完好,何必再用friend重载,直接在类外部定义重载,而且就算需要在类里面进行重载,声明也应该放在public里,默认情况下为私有成员,类对象没有对它的特殊访问权限,那句声明也是不对的

#include <iostream>
#include <iomanip>
using namespace std;
#ifndef POINT_H
#define POINT_H

class point
{
int x,y;
public:
// friend ostream &operator<<(ostream &,const point &);
point(int = 0, int