简体   繁体   English

模板是否需要重载构造函数?

[英]Do templates need overloaded constructors?

I just finished watching some videos of template and I think I am missing some concepts. 我刚看完一些模板视频,我想我错过了一些概念。 Why doesn't the constructor get called, or why the object is not created when the constructor is not overloaded with a desired data-type? 为什么不调用构造函数,或者为什么在构造函数没有使用所需的数据类型重载时不创建对象? Since I am writing the <int> doesn't the compiler know I am going to be dealing with an int? 由于我正在编写<int> ,编译器是否知道我将处理一个int?

template <class T>
class Generic {
    T var;
public:
    Generic(){cout << "ctor called " << endl;}
    //Generic (T v) {var = v;}
};


int main () {

    Generic<int> generic1();

}

Can't I create an object like this and then modify the value of T var through a setter? 我不能创建这样的对象然后通过setter修改T var的值吗? Why should I need an overloaded constructor eg Generic<int> generic1(9); 为什么我需要一个重载的构造函数,例如Generic<int> generic1(9); ?

This is a Most vexing parse issue. 这是一个最令人烦恼的解析问题。

Of course you can initialize the object via the default constructor, and modify the value via a setter later, the problem here is that you're not defining a variable. 当然你可以通过默认的构造函数初始化对象,然后通过setter修改值,这里的问题是你没有定义变量。 Generic<int> generic1(); is a declaration of function, which is named generic1 , takes no arguments and returns Generic<int> . 是函数声明,名为generic1 ,不带参数并返回Generic<int>

What you want is 你想要的是什么

Generic<int> generic1;

or 要么

Generic<int> generic1{}; // since C++11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM