如何在C++中使用类对象访问指针数据成员
How to access pointer data member using class object in C++?
我有以下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();
相关文章:
- 按基类对象访问派生类资源时出错
- 使用基类对象访问派生的仅类方法
- 从 const 对象访问非 const 方法
- 如何在C++中使用类对象访问指针数据成员
- 如何通过不同的指针使用类的对象访问结构?(链表)(C++)
- 使用二进制搜索树中的迭代器对象访问左侧节点
- 为什么引用类型在使用临时对象访问时是左值
- 从父对象 c++ 访问子方法
- 无法通过指针或对象 c++ 访问受保护的成员
- 为什么可以从类中的对象访问类的私有变量
- 对类似"struct {double, int}"对象使用reinterpret_cast进行对象访问
- 通过无符号 char 别名进行对象访问,加载和存储时会发生什么?
- 从对象访问结构枚举
- 如何全局创建对象并使用该对象访问全局范围内的公共成员函数
- 在C 中,可以从第三个共享对象访问其他两个不同共享对象
- 如何在C 中提供一个可呼叫的对象访问,例如lambda
- C 向量对象访问
- C++是否可以从同级第二个派生对象访问第一个派生对象的受保护基础数据成员?
- 如何从类内实例化的对象访问私有变量
- 多态性:通过类文本或对象访问静态成员