如何在C++中使用类对象访问指针数据成员?

Viv*_*rma -2 c++ pointers

我有以下内容code

class FLOAT    
{
    float *num;

public:
    FLOAT(){}
    FLOAT(float f)
    {
        num = new float(f);
    }

    FLOAT operator +(FLOAT& obj)
    {
        FLOAT temp;
        temp.num = new float;

        temp.num = *num + obj.getF();
        return temp;    
    }

    float getF(){ return *num; }
    void showF(){ cout << "num : "<< *num << endl; }
};
Run Code Online (Sandbox Code Playgroud)

它显示一个错误。

我的问题是,如何使用类对象访问该float *num数据成员?

Rem*_*eau 5

你们班上有很多错误。这根本就是设置不正确。

  • 该类的默认构造函数float根本不分配。

  • 该班级不遵循3/5/0 规则。它缺少用于释放浮点的析构函数、用于安全复制浮点的复制构造函数和复制赋值运算符,并且在 C++11 及更高版本中,缺少用于在之间安全移动浮点的移动构造函数和移动赋值运算符对象。

  • operator+当为浮点数分配新值时,您没有取消对指针的引用。

试试这个:

class FLOAT
{
    float *num;

public:
    FLOAT(float f = 0) : num(new float(f)) {}

    FLOAT(const FLOAT &src) : num(new float(*(src.num))) {}

    // in C++11 and later...
    FLOAT(FLOAT &&src) : num(src.num) { src.num = nullptr; }
    // alternatively:
    // FLOAT(FLOAT &&src) : num(nullptr) { std::swap(num, src.num); }

    ~FLOAT() { delete num; }

    FLOAT& operator=(const FLOAT &rhs)
    {
        *num = *(rhs.num);
        return *this;
    }

    // in C++11 and later...
    FLOAT& operator=(FLOAT &&rhs)
    {
        std::swap(num, rhs.num);
        return *this;
    }

    FLOAT operator+(const FLOAT& rhs)
    {
        FLOAT temp;
        *(temp.num) = *num + rhs.getF();
        return temp;

        // or simply:
        // return *num + rhs.getF();
    }

    float getF() const { return *num; }
    void showF() { cout << "num : " << *num << endl;    }
};
Run Code Online (Sandbox Code Playgroud)

话虽如此,根本没有充分的理由动态分配浮动(除非作为学习经验)。让编译器为您处理内存管理:

class FLOAT
{
    float num;

public:
    FLOAT(float f = 0) : num(f) {}

    FLOAT(const FLOAT &src) : num(src.num) {}

    FLOAT& operator=(const FLOAT &rhs)
    {
        num = rhs.num;
        return *this;
    }

    FLOAT operator+(const FLOAT& rhs)
    {
        FLOAT temp;
        temp.num = num + rhs.getF();
        return temp;

        // or simply:
        // return num + rhs.getF();
    }

    float getF() const { return num; }
    void showF() { cout << "num : " << num << endl; }
};
Run Code Online (Sandbox Code Playgroud)

然后可以通过让编译器隐式定义复制构造函数和复制赋值运算符来稍微简化:

class FLOAT
{
    float num;

public:
    FLOAT(float f = 0) : num(f) {}

    FLOAT operator+(const FLOAT& rhs)
    {
        FLOAT temp;
        temp.num = num + rhs.getF();
        return temp;

        // or simply:
        // return num + rhs.getF();
    }

    float getF() const { return num; }
    void showF() { cout << "num : " << num << endl; }
};
Run Code Online (Sandbox Code Playgroud)