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

公有继承

大剑 发布于 2011-11-20 21:14, 687 次点击
问两个问题  小弟新手 问的幼稚请莫见怪
程序如下
#include "stdafx.h"
#include <iostream>
#include "math.h"
using namespace std;
class CRect
{  
    float length;
protected:
    float width;
    float get_length() { return length;}
public:
    float area(){return length * width;}
    CRect(float l,float w)
    { length=l;width=w;}
};
class CParal:public CRect
{
    float angle;
public:
    float area() {return (float)(length * width * sin(angle));}//erro
    CParal(float l,float w,float f):CRect(l,w)
    {
        angle=f;
    }
};
float PI=3.14;
void main()
{
    CParal paral(10,12,PI/6);
    cout<<"The area of paral is: "<<paral.area()<<endl;
}
 错误提示是这样的 error C2248: 'CRect::length' : cannot access private member declared in class 'CRect'
意思是否是length 是基类的的私有成员 不能直接访问  但我已经加了这句 float get_length() { return length;}
了啊   我开头这样写对不对#include "stdafx.h"
#include <iostream>
#include "math.h"
using namespace std;
2 回复
#2
rjsp2011-11-21 08:26
class CRect
{
public:
    CRect( float length, float width ) : length_(length), width_(width)
    {
    }
    virtual ~CRect()
    {
    }
    virtual float area() const
    {
        return length_ * width_;
    }
    float get_length() const
    {
        return length_;
    }
    float get_width() const
    {
        return width_;
    }
private:
    float length_, width_;
};

#include <cmath>

class CParal : public CRect
{
public:
    CParal(float length, float width, float angle) : CRect(length,width), angle_(angle)
    {
    }
    virtual ~CParal()
    {
    }
    virtual float area() const
    {
        return (float)( get_length() * get_width() * sin(angle_) );
    }
    float get_angle() const
    {
        return angle_;
    }
private:
    float angle_;
};

#include <iostream>
using namespace std;

const float PI = 3.14f;

int main()
{
    CParal paral(10,12,PI/6);
    cout << "The area of paral is: " << paral.area() << endl;

    return 0;
}
#3
kscooh12011-11-21 09:30
私有的不能直接使用 只能调用函数
我改的可以运行了:
程序代码:
//#include "stdafx.h"
#include <iostream>
#include "math.h"
using namespace std;
class CRect
{
    float length;
protected:
    float width;
    float get_length() { return length;}
public:
    float area(){return length * width;}
    CRect(float l,float w)
    { length=l;width=w;}
};
class CParal:public CRect
{
    float angle;
public:
    float area() {return (float)(get_length() * width * sin(angle));}//erro
    CParal(float l,float w,float f):CRect(l,w)
    {
        angle=f;
    }
};
const float PI=3.14;
void main()
{
    CParal paral(10,12,PI/6);
    cout<<"The area of paral is: "<<paral.area()<<endl;
}

1