不调用合适的构造函数
#include<iostream>
using namespace std;
class String
{
protected:
enum {SZ= 80};
char str[SZ];
public:
String (){str[0]='\0';}
String(char s[])
{
strcpy(str,s);
}
void display() const
{
cout<<str;
}
operator char*()
{
return str;
}
};
class Pstring : public String
{
public:
Pstring(char s[])
{
if(strlen(s)>SZ-1)
{
for(int j=0;j<SZ-1;j++)
{
str[j]=s[j];
}
str[SZ-1]='\0';
}
else
{String(s);}
}
};
int main()
{
Pstring s2 ="This is a strong string.";
cout<<"\ns2="; s2.display();
return 0;
}
s2.display()
返回空白。调试后,发现string(s)
在PSTRING中调用字符串类中的no-argument构造函数。我将其理解为具有一个参数的构造函数,因此应该调用字符串(char s [])
。这是什么行为?
#include<iostream>
using namespace std;
class String
{
protected:
enum {SZ= 80};
char str[SZ];
public:
String (){str[0]='\0';}
String(char s[])
{
strcpy(str,s);
}
void display() const
{
cout<<str;
}
operator char*()
{
return str;
}
};
class Pstring : public String
{
public:
Pstring(char s[])
{
if(strlen(s)>SZ-1)
{
for(int j=0;j<SZ-1;j++)
{
str[j]=s[j];
}
str[SZ-1]='\0';
}
else
{String(s);}
}
};
int main()
{
Pstring s2 ="This is a strong string.";
cout<<"\ns2="; s2.display();
return 0;
}
s2.display()
returns blank. Upon debugging it's is found that String(s)
in Pstring calls the no-argument constructor in the String class. I understand it as a constructor with one argument and thus String(char s[])
should've been called. What is this behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此代码段
是没有意义的。
这一行
是类型
String
的变量s
的声明,并具有IF语句ELSEN的复合操作员的范围。请注意该构造函数
在将控件的正文传递给构造函数之前,隐式称为类字符串的默认构造函数。这就是构造函数的主体只有在创建派生类创建对象的所有子对象之后才能创建控件。
您应该在类
String
的构造函数中将传递字符串的检查放置。例如,在类
字符串
中,您可以使用以下方式定义构造函数,并且可以像定义派生类中的构造函数一样定义
This code snippet
does not make a sense.
This line
is a declaration of the variable
s
of the typeString
with the scope of the compound operator of the else part of the if statement.Pay attention to that this constructor
calls implicitly the default constructor of the class String before the control will be passed to the body of the constructor. That is the body of the constructor gets the control only after all sub-objects of the created object of the derived class will be created.
You should place the check of the passed string in the constructor of the class
String
.For example in the class
String
you could define the constructor with parameter the following wayAnd the constructor in the derived class could be defined like