c++ - 在 main() 中为通用模板类选择数据类型

标签 c++ arrays templates generics dynamic

所以我被要求编写一个简单的 vector 模板,我相信我已经正确地编写了这个类,查看了我们教科书 (Savitch) 中的一些广义列表示例。现在我试图通过让用户选择数据类型来调用 main() 中的类。声明标识符 list1 后,我遇到了问题。我希望在使用 if 语句切换数据类型后能够使用相同的标识符。但是,我认为 if 语句主体中的语法不正确,因为 list1 已经声明。在 java 中,我一直认为在声明一个类之后,您可以随时调用它的构造函数,但我不知道如何在 C++ 中执行此操作。

#include <iostream>
using namespace std;

template <class T>
class SimpleVector {
    public:
        SimpleVector();
        SimpleVector(int);
        SimpleVector(const SimpleVector & copy);
        ~SimpleVector();
        int size();
        T getElementAt(int n);
        T & operator[](int index);

    private:
        T * item;
        int length;
};


int main() {


    int dType;
    int dataSize;

    cout << "What type of data do you want to enter?\n(1 for integer, 2 for double and 3 for strings)" << endl;
    cin >> dType;
    cout << "How many data inputs? " << endl;
    cin >> dataSize;

    SimpleVector <int> list1; // if I dont declare then for loop doesn't recognize list as a declared variable.
    if (dType == 0) {
        SimpleVector <int> list1(dataSize);
    }
    else if (dType == 1) {
        SimpleVector <double> list1(dataSize);
    }
    else {
        SimpleVector <string> list1(dataSize);
    }

    cout << "Please enter the data:" << endl;
    for (int i = 0; i < dataSize; i++) {
        cin >> list1[i];
    }



    return 0;
}

template <class T> SimpleVector<T>::SimpleVector() {
    item = NULL;
    length = 0;
}
template <class T> SimpleVector<T>::SimpleVector(int s) {
    length = s;
    item = new T[length];

}

template <class T> SimpleVector<T>::SimpleVector(const SimpleVector & copy) {
    int newSize = copy - > size();
    item = new T[newSize];

    for (int i = 0; i < newSize; i++)
    item[i] = copy.item[i];
}

template <class T> SimpleVector<T>::~SimpleVector() {
    delete[] item;
}

template <class T> int SimpleVector<T>::size() {
    return length;
}

template <class T> T SimpleVector<T>::getElementAt(int n) {
    return *(item + n);
}

template <class T> T & SimpleVector<T>::operator[](int index) {
    return this->item[index];
}

最佳答案

您不能切换数据类型。变量一旦声明为特定类型就不能更改为其他类型。

变量有范围。

{
    int a;
    .....stuff.....
}
// a cannot be accessed here.

a 现在只能在打开的 { 和关闭的 } 之间使用。

{
    int a; // First a
    .....stuff..... // a refers to the first a here
        {
            int a;
            .....stuff..... // a refers to the second a here
        }
    .....stuff..... // a refers to the first a here
}

第二个 a 是与第一个不同的变量。它只能在它的范围内访问 - 即在离它最近的左括号和右括号之间。

如果您真的想要动态类型,请尝试 Boost.variantBoost.Any

关于c++ - 在 main() 中为通用模板类选择数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13676674/

相关文章:

c++ - C++访问静态结构,需要初始化

C++ const 成员函数

javascript - Ember JS 如何获取具有唯一属性值的数组

c++ - 将类作为模板参数,并将类构造函数的参数作为方法参数的方法

JAVA:我无法从套接字读取文本,由 C++ 程序发送

c++ - 为什么不总是构建带有调试信息的版本?

php - 如果使用 group by 进行 mysql SUM 查询时没有记录,则将其设为 0 而不是 null

arrays - Lua 表是如何在内存中处理的?

c++ - 友元模板函数的正确语法

c++ - 模板类中的函数定义