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

类定义的问题,求教

G梦 发布于 2013-08-17 13:23, 907 次点击
部分代码:
class CLine
{
public:
    CLine(){}
    CLine(float X1=0,X2=0,Y1=0,Y2=0)
    {
        x1=X1;    x2=X2;  y1=Y1;  y2=Y2;
    }
    void Length()
    {
        int k;
        k= sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
        cout<<k<<endl;
    }
    void show()
    {
        cout<<'('<<x1<<','<<y1<<')'<<endl;
        cout<<'('<<x2<<','<<y2<<')'<<endl;
    }

private:
    float x1;
    float x2;
    float y1;
    float y2;
};



error C2629: unexpected 'class CLine (';
error C2334: unexpected token(s) preceding '{'; skipping apparent function body;
这到底是哪儿出错了??
10 回复
#2
rjsp2013-08-17 15:41
你贴的代码中根本就没有 'class CLine (',你还是将代码贴完整些。
对于你已有的代码,当如下修改
程序代码:
#include <cmath>
#include <iostream>

class CLine
{
public:
    explicit CLine( float X1=0.0f, float Y1=0.0f, float X2=0.0f, float Y2=0.0f ) : x1_(X1), y1_(Y1), x2_(X2), y2_(Y2)
    {
    }
    float length() const
    {
        return sqrt( (x1_-x2_)*(x1_-x2_) + (y1_-y2_)*(y1_-y2_) );
    }

private:
    float x1_, y1_;
    float x2_, y2_;

    friend std::ostream& operator<<( std::ostream& os, const CLine& line );
};

std::ostream& operator<<( std::ostream& os, const CLine& line )
{
    return os<<"[("<<line.x1_<<','<<line.y1_<<"),("<<line.x2_<<','<<line.y2_<<")]";
}

using namespace std;

int main()
{
    CLine line( 0.0f, 0.0f, 4.0f, 3.0f );
    cout << line << " length is " << line.length() << endl;

    return 0;
}

#3
peach54602013-08-17 16:39
他贴的代码感觉没问题
#4
rjsp2013-08-17 16:41
回复 3楼 peach5460
起码 CLine(float X1=0,X2=0,Y1=0,Y2=0) 就不可以吧,因为X2,Y1,Y2都没写类型
#5
peach54602013-08-18 06:51
回复 4楼 rjsp
额...我错了...
#6
zhujiangtaoc2013-08-18 10:20
4楼很对啊
#7
TonyDeng2013-08-18 12:36
构造函数那里缺了分号,不要以为空花括号就不用括号了。其实,如果你这构造函数是什么也不干的,不用写这行,自有默认构造函数,就算有自己的内容,只写圆括号后带分号就可以了,在实现部分写上代码,再退一步,实在要写,在花括号里面写个空语句,即一个分号。空花括号,叫编译器怎么理解你到底要干什么?编译信息明明告诉你是花括号问题。

[ 本帖最后由 TonyDeng 于 2013-8-18 12:41 编辑 ]
#8
TonyDeng2013-08-18 12:39
error C2334: unexpected token(s) preceding '{'; skipping apparent function body;

这个信息说花括号那里看来跳过了函数体。

[ 本帖最后由 TonyDeng 于 2013-8-18 12:40 编辑 ]
#9
未未来2013-08-19 16:41
CLine(float X1=0,X2=0,Y1=0,Y2=0) 四个参数就算同一类型,也必须重复声明
#10
G梦2013-08-24 13:08
谢谢大家,发现我还是没注意到好多小的知识点
#11
TonyDeng2013-08-24 19:50
不是你没注意,而是没有养成相信编译器的关系,编译器给出信息才是正解,看到了又不去查字典求理解,总想别人来解,这样是无法自主学下去的。没有谁是总靠别人扶着走能成功的,所谓的高手都是靠自己摸索出来的,学会摸索比求得别人解答重要得多。
1