调用构造函数的语句,但不对其执行任何操作 - 为什么它不编译?

发布于 2024-12-19 12:12:55 字数 766 浏览 5 评论 0原文

我们可以有一个调用构造函数但不执行任何操作的语句吗?

基本上,我重载构造函数,并使用构造函数而不将其分配给变量,就像我们通常所做的那样。 (通常我们不会这样做,但我可能会在使用函子时看到这种情况出现。)

有什么想法吗?....(我已将复制构造函数声明为私有,只是为了确保这不是导致问题。)

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

聊慰 2024-12-26 12:12:55

由于 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 say int(r); to declare r.)

油焖大侠 2024-12-26 12:12:55

myClass (r); 行实际上被解释为 myClass 类型的 r 变量的定义 (myClass r;),它已被定义为 int

The myClass (r); line is actually interpreted as a definition of the r variable of type myClass (myClass r;), which is already defined as int.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文