【发布时间】:2016-02-02 22:44:30
【问题描述】:
这个示例程序显示了如何调用不同的构造函数,具体取决于您传入的是局部变量、全局变量还是匿名变量。这是怎么回事?
std::string globalStr;
class aClass{
public:
aClass(std::string s){
std::cout << "1-arg constructor" << std::endl;
}
aClass(){
std::cout << "default constructor" << std::endl;
}
void puke(){
std::cout << "puke" << std::endl;
}
};
int main(int argc, char ** argv){
std::string localStr;
//aClass(localStr); //this line does not compile
aClass(globalStr); //prints "default constructor"
aClass(""); //prints "1-arg constructor"
aClass(std::string("")); //also prints "1-arg constructor"
globalStr.puke(); //compiles, even though std::string cant puke.
}
鉴于我可以调用globalStr.puke(),我猜想通过调用aClass(globalStr);,它会创建一个名为globalStr 类型为aClass 的局部变量,而不是全局globalStr。调用aClass(localStr); 会尝试做同样的事情,但编译失败,因为localStr 已经被声明为std::string。是否可以通过使用非常量表达式调用其 1-arg 构造函数来创建类的匿名实例?谁决定 type(variableName); 应该是定义名为 variableName 的变量的可接受方式?
【问题讨论】:
-
什么是匿名构造函数?我不知道有这样的事情。
-
Well, that's interesting,为什么
puke()可以在std::string类上调用。 -
@πάνταῥεῖ,它被
globalStr在main中的声明所掩盖。 -
这是我所见过的使用
{..}来构造对象而不是(..)的最佳动机之一。 -
C++(和 C,就此而言)允许您在声明标识符时将括号括起来。声明函数指针时实际上需要这种语法:
aClass (*fptr)(std::string)
标签: c++ anonymous default-constructor