【问题标题】:What is the difference between MyRectangle mr = MyRectangle(); and MyRectangle mr2 (); [duplicate]MyRectangle mr = MyRectangle(); 有什么区别?和 MyRectangle mr2 (); [复制]
【发布时间】:2013-05-07 16:51:46
【问题描述】:

我注意到,即使构造函数没有参数,前者也会进入我制作的构造函数,而后者只有在需要参数时才会进入我制作的构造函数。

// ConsoleApplication11.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
#include "string"

using namespace std;


class myRectangle {
    int width;
    public:
        int getWith();
        void setWidth(int newWidth) {width = newWidth;};
        myRectangle (int);
        ~myRectangle ();
};
myRectangle::myRectangle (int w) {
    width = w;
    cout << "myRectangel Constructor\n";
}

myRectangle::~myRectangle() {
    cout << "destructor\n";
}

void runObject();

int _tmain(int argc, _TCHAR* argv[])
{
    runObject();
    int exit; cout << "\n\n"; 
    cin >> exit;
    return 0;
}

void runObject() 
{
    myRectangle mr (5);
}

失败 // ConsoleApplication11.cpp : 定义控制台应用程序的入口点。 //

#include "stdafx.h"
#include "iostream"
#include "string"

using namespace std;


class myRectangle {
    int width;
    public:
        int getWith();
        void setWidth(int newWidth) {width = newWidth;};
        myRectangle ();
        ~myRectangle ();
};
myRectangle::myRectangle () {
    cout << "myRectangel Constructor\n";
}

myRectangle::~myRectangle() {
    cout << "destructor\n";
}

void runObject();

int _tmain(int argc, _TCHAR* argv[])
{
    runObject();
    int exit; cout << "\n\n"; 
    cin >> exit;
    return 0;
}

void runObject() 
{
    myRectangle mr ();
}

【问题讨论】:

标签: c++


【解决方案1】:
myRectangle mr(5);

这里,mr 是一个 myRectangle 实例,使用带有单个 int 参数的 myRectangle 构造函数构造。

myRectangle mr ();

这里,mr 是一个没有参数并返回 myRectangle 的函数。这是一个令人困惑的解析,可以通过使用大括号初始化在 C++11 中避免。也可以通过省略括号来避免:

myRectangle mr; //  C++03 and C++11
myRectangle{};  //  C++11

【讨论】:

    【解决方案2】:

    myRectangle mr = myRectangle(); 实例化并构造类myRectangle 的实例。相比之下,myRectangle mr ();mr 声明为返回 myRectangle 且不带任何参数的函数。

    【讨论】:

    • 你可能注意到Foo f = Foo();存在复制省略
    【解决方案3】:

    内部:

     void runObject() 
     {
         myRectangle mr ();
     }
    

    myRectangle mr(); 不是创建myRectangle 的对象,而是声明了一个名为mr 的函数,它不带参数,返回类型为myRectangle

    【讨论】:

    • 也许对你来说,但对编译器来说不是。要在不使用构造函数参数的情况下实例化对象,请省略括号:myRectangle me;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 2013-02-13
    • 2011-04-26
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多