注册 登录
编程论坛 C++教室

求助:书上示例一句编译时出错如何改?

bardon 发布于 2011-02-13 22:04, 493 次点击
这是自考教材上的有关用友元函数求两点间距离的程序:
class Location{
private: float X,Y;
public:
    Location(float xi,float yi){X=xi;Y=yi;}
    float GetX(){return X;}
    float GetY(){return Y;}
    friend float distance(Location& a,Location& b);
};
   
        float distance(Location& a,Location& b)
    {
        float dx=a.X-b.X;
        float dy=a.Y-b.Y;
        return sqrt(dx*dx+dy*dy);
        
    }

void main(){

    Location p1(6,9),p2(9,6);
  float d = distance(p1,p2);
//  仅上句编译不能通过,请大虾指点如何修改,谢谢。
    cout<<"The distance is:"<<d<<endl;
}
5 回复
#2
BlueSKySea2011-02-14 00:25
没错啊,在2008里试了下,是可以的啊
// newtest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <math.h>

class Location
{
private: float X,Y;
public:
    Location(float xi,float yi){X=xi;Y=yi;}
    float GetX(){return X;}
    float GetY(){return Y;}
    friend float distance(Location& a,Location& b);
};

float distance(Location& a,Location& b)
{
    float dx=a.X-b.X;
    float dy=a.Y-b.Y;
    return sqrt(dx*dx+dy*dy);

}

void main(){

    Location p1(6,9),p2(9,6);
    float d = distance(p1,p2);
    //  仅上句编译不能通过,请大虾指点如何修改,谢谢。
    std::cout<<"The distance is:"<<d<<std::endl;
}
#3
pangding2011-02-14 01:40
你的编译器报的什么错?
#4
bardon2011-02-14 23:21
就那一行程序,报了很多行错,故也就不知是说些什么了。
用的是Visual Studio 2010,也许是编程软件的问题?
谢谢各位指点,再找一个编程软件试试看。

[ 本帖最后由 bardon 于 2011-2-14 23:24 编辑 ]
#5
rjsp2011-02-15 08:19
程序代码:
class Location
{
    friend double distance( const Location& a, const Location& b );
public:
    Location( double x, double y ) : x_(x), y_(y) {}
    double GetX() const { return x_; }
    double& GetX() { return x_; }
    double GetY() const { return y_; }
    double& GetY() { return y_; }
private:
    double x_, y_;
};

#include <cmath>
double distance( const Location& a, const Location& b )
{
    return sqrt( (a.x_-b.x_)*(a.x_-b.x_) + (a.y_-b.y_)*(a.y_-b.y_) );
}

#include <iostream>
using namespace std;

int main()
{
    Location p1(6.0,9.0), p2(9.0,6.0);
    double d = ::distance(p1,p2); // 使用 ::distance 以便和 std::distance 区分开来
    cout << "The distance is:" << d <<endl;

    return 0;
}

#6
bardon2011-02-15 11:02
回复 5楼 rjsp
谢谢楼上大虾指点,用修改后的语句就能编译通过了。
若是不修改,改用另一编程软件“C与C++程序设计学习与实验系统 2011”
也能编译通过,谢谢各位指点。
1