调用构造函数的语句,但不对其执行任何操作 - 为什么它不编译?
我们可以有一个调用构造函数但不执行任何操作的语句吗?
基本上,我重载构造函数,并使用构造函数而不将其分配给变量,就像我们通常所做的那样。 (通常我们不会这样做,但我可能会在使用函子时看到这种情况出现。)
有什么想法吗?....(我已将复制构造函数声明为私有,只是为了确保这不是导致问题。)
class myClass
{
public:
myClass (int n, int x) { }
myClass (int n ) { }
private:
myClass (const myClass & t){} // copy constructor is private.....
};
int main()
{
int r = 5;
myClass A( r ); // OK (as per usual)
myClass ( r, r ); // OK
myClass ( 5 ); // OK
myClass ( r ); // not OK : error C2371: 'r' : redefinition; different basic types
// myClass B = myClass ( r ); // this would not work as copy constructor
// has been declared as private
return 0;
}
Can we have a statement that calls a constructor, and does nothing with it?
Basically, am overloading the constructor, and using the constructors without assigning it to a variable, as we would usually.
(Normally we wouldn't do this, but I could see this arising when using functors, possibly.)
Any ideas?.... (I have declared the copy constructor as private, just to make sure that this was not the cause of the problem.)
class myClass
{
public:
myClass (int n, int x) { }
myClass (int n ) { }
private:
myClass (const myClass & t){} // copy constructor is private.....
};
int main()
{
int r = 5;
myClass A( r ); // OK (as per usual)
myClass ( r, r ); // OK
myClass ( 5 ); // OK
myClass ( r ); // not OK : error C2371: 'r' : redefinition; different basic types
// myClass B = myClass ( r ); // this would not work as copy constructor
// has been declared as private
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于 C++ 的解析规则,您必须说
(myClass(r));
,并带有额外的括号。(您所说的是一个名为
r
的新变量的声明,该变量已经存在。请注意,您也可以说int(r);
来声明r
。)You have to say
(myClass(r));
, with the extra parentheses, due to the parsing rules of C++.(What you said is a declaration of a new variable of name
r
, which already exists. Note that you can also sayint(r);
to declarer
.)myClass (r);
行实际上被解释为myClass
类型的r
变量的定义 (myClass r;),它已被定义为
int
。The
myClass (r);
line is actually interpreted as a definition of ther
variable of typemyClass
(myClass r;
), which is already defined asint
.