C++中的构造函数调用模糊性
Constructor calling ambiguity in C++
#include <string.h>
#include <iostream>
using namespace std;
class String
{
public:
/* Parameterized Constructor */
String(const char* i_ac)
{
cout<<"Parameterized Constructor";
if(i_ac)
{
data = new char [strlen(i_ac) + 1];
strcpy(data,i_ac);
}
else
{
data = new char[1];
*data = ' ';
}
}
//Parametrized constructor ends.
/*Copy Constructor */
String ( String& objTemp )
{
cout<<"Copy Constructor";
data = new char[strlen(objTemp.data) + 1];
strcpy(data,objTemp.data);
}
/*Overloaded Assignment Operator */
String operator=(String& objTemp)
{
if(this == &objTemp)
return objTemp;
//Delete Existing data
delete[] data;
data = new char[strlen(objTemp.data)+ 1];
strcpy(data,objTemp.data);
return *this;
}
friend ostream& operator<<(ostream& out, String& s1);
private :
char* data;
};
ostream& operator<<(ostream& o1, String& s1)
{
o1<<s1.data;
return o1;
}
int main()
{
String s1("Hello");
cout<<"s1"<<s1;
String s2 = s1;
cout<<"ns2"<<s2;
String s3(); //doubt
cout<<"ns3"<<s3;
}
在调用String s3()
时,不会调用任何构造函数(我知道,因为我在每个构造函数内部打印)。但是,在下一行打印s3
会输出1。
为什么没有调用构造函数?我怎样才能确保一个被调用?
只需注意:请尝试clang,它有一些非常好的诊断:
t.cpp:64:10: warning: empty parentheses interpreted as a function declaration [-Wvexing-parse]
String s3(); //doubt
^~
t.cpp:65:15: warning: address of function 's3' will always evaluate to 'true' [-Wbool-conversion]
cout<<"ns3"<<s3;
~~~~ ^~
t.cpp:65:15: note: prefix with the address-of operator to silence this warning
cout<<"ns3"<<s3;
^
&
2 warnings generated.
为什么不调用构造函数?我怎样才能确保一个被调用?
这将不起作用,它不会调用空的ctor,而是创建一个本地方法。
String s3(); //doubt
cout<<"ns3"<<s3;
要实现此操作,请从Strings3()中删除();成为字符串s3;
String s3; // This is the correct form
(我认为这是刚开始使用C++时最常见的错误之一)但请注意,这将触发链接器错误,因为您没有定义空的ctor。我猜您希望使用"参数化"的ctor作为空的ctor,也基于其中的if/else条件。为此,您必须为参数i_ac指定默认值0或NULL。或者,如果您使用的是C++11,请使用nullptr,因为NULL被认为是令人厌恶的。
旁注:
但是,在下面的行打印s3会输出1。
这将把s3求值为bool,因此您会输出"1"。
/*Copy Constructor */
String ( String& objTemp )
这真的应该写成
/*Copy Constructor */
String ( const String& objTemp )
也是如此
/*Overloaded Assignment Operator */
String operator=(String& objTemp)
// Add const
String operator=(const String& objTemp)
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- C++如何抛弃函数的虚拟性并调用基本函数,而不是覆盖
- 类X有多个默认构造函数和对重载函数的模糊调用
- 对C++基类的模糊函数调用
- C++中的构造函数调用模糊性
- C++:用单个函数调用替换多个索引相等性测试
- Visual Studio不允许我使用sqrt或floor,对重载函数的模糊调用
- 非成员函数中的隐式参数转换模糊性使用std::函数重载
- c++中的函数重载模糊性
- Visual Studio 2012中嵌套boost::assign:list_of失效-对重载函数的模糊调用
- 涉及模板化转换操作符和隐式复制构造函数的模糊性
- 模板函数调用模糊性错误