2016-09-26 128 views
-4

我想为类CLS定义一个构造函数。我想在我的构造函数的定义中包含不同的情况。例如,我希望构造函数在参数无效时工作: CLS :: CLS();在C++中,如何使构造函数具有不同类型的参数?

或者当参数是一个整数时, CLS :: CLS(int a);

我该怎么做?

+6

写两个构造 – StenSoft

+2

您也可以利用[默认参数](http://en.cppreference.com/w/cpp/language/default_arguments) 。例如。 'CLS(int a = 0);' – user4581301

+0

请在询问Stack Overflow之前咨询Google。您可能会因为简单的搜索找到答案而陷入低谷:https://www.google.com/webhp?sourceid=chrome-instant&rlz=1C1CHFX_enUS594US594&ion=1&espv=2&ie=UTF-8#q=c%2B%2B %20constructors%20with%20different%20arguments –

回答

1

在我看来,你的问题实际上过于笼统。

一般的答案是function overloading

总之,你可以简单地写出两个不同的函数(在这种情况下的方法)具有相同的名称,但不同的参数。你可以为每个人指定一个不同的身体。例如:

class CLS { 
public: 
    CLS(int n) { 
    // do something 
    } 

    CLS(char c) { 
    // do something else 
    } 
}; 

然后,你可以简单地构造一个对象:

// ... somewhere 
CLS object1(12); // 12 is a int, then the first 'ctor will be invoked 
CLS object2('b'); // 'b' is a char, the second 'ctor will be invoked, instead. 

A “招进” 的答案,需要模板的使用。

总之,您可以编写一个接受类型的泛型类型的构造函数作为参数,并指定该类型遵循某些特征时的行为。当你可以“概括”(几乎所有的机构)

class CLS { 
public: 
    template<typename T> 
    CLS(T t) { 
    if (std::is_arithmetic<T>::value) { 
     // do something if the type is an arithmetic 
    } else { 
     // do something else 
    } 
    } 
}; 

这种方法可能是有用的构造函数的行为,以及你想要聚合不同类型的。

0

另一种方法是利用Default Arguments。例如

#include <iostream> 

class example 
{ 
public: 
    int val; 
    example(int in = 0): val(in) 
    { 

    } 
}; 

int main() 
{ 
    example a(10); 
    example b; 

    std::cout << a.val << "," << b.val << std::endl; 
} 

将输出

10,0 
相关问题