定定义一个DataType(数据类型)类,能处理包含字符型、整型、浮点型三种类型的数 据,给出其构造函数。用C++定义
时间: 2024-10-29 13:25:11 浏览: 130
在C++中,我们可以定义一个名为`DataType`的类来处理字符型(char), 整型(int)和浮点型(float)的数据。首先,我们需要包含必要的头文件,并定义构造函数初始化不同类型的数据。下面是一个简单的例子:
```cpp
#include <iostream>
using namespace std;
class DataType {
public:
// 构造函数,接受并存储数据
explicit DataType(string dataType, union DataUnion value) {
this->dataType = dataType;
this->value = value;
}
private:
string dataType; // 数据类型字符串
union {
char cChar;
int iInt;
float fFloat;
} value; // 包含所有数据类型的联合体
// 根据数据类型设置正确的值域
void setChar(char val) { value.cChar = val; }
void setInt(int val) { value.iInt = val; }
void setFloat(float val) { value.fFloat = val; }
// 获取值(根据数据类型)
char getChar() const { return value.cChar; }
int getInt() const { return value.iInt; }
float getFloat() const { return value.fFloat; }
};
int main() {
// 示例创建一个DataType对象
DataType myData("char", 'A');
cout << "Character: " << myData.getChar() << endl;
myData.dataType = "int";
myData.setInt(42);
cout << "Integer: " << myData.getInt() << endl;
myData.dataType = "float";
myData.setFloat(3.14);
cout << "Floating point: " << myData.getFloat() << endl;
return 0;
}
```
在这个例子中,我们使用了C++的`union`来同时存储三种类型的数据,然后通过`setChar`, `setInt`, 和 `setFloat`方法以及对应的getter函数来访问数据。构造函数接收数据类型和对应值,并在内部进行转换。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)