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

How to access pointer data member using class object in C++?

本文关键字:对象 访问 指针 数据成员 C++      更新时间:2023-10-16

我有以下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; }
};

它显示了一个错误。

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

您的类中有很多错误。它根本没有正确设置。

  • 类的默认构造函数根本没有分配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;    }
};

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

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; }
};

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

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; }
};

当您分配以下语句时:

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

实际上,您将浮点number分配给了浮点pointer

因此,使用以下内容:

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

代替:

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