我注意到前者进入我构造的构造函数,即使构造函数没有参数,而后者只进入我只在需要参数时才构造的构造函数。
WIN
// 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);
}
FAIL // 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 ();
}
答案 0 :(得分:3)
myRectangle mr(5);
这里,mr
是一个myRectangle
实例,使用myRectangle
构造函数构造,该构造函数接受一个int参数。
myRectangle mr ();
此处,mr
是一个没有参数且返回myRectangle
的函数。这是一个令人困惑的解析,可以通过使用大括号初始化在C ++ 11中避免。省略括号也可以避免:
myRectangle mr; // C++03 and C++11
myRectangle{}; // C++11
答案 1 :(得分:1)
内部:
void runObject()
{
myRectangle mr ();
}
myRectangle mr();
没有创建myRectangle
的对象,而是声明一个名为mr
的函数,该函数不带参数,返回类型为myRectangle
。
答案 2 :(得分:1)
myRectangle mr = myRectangle();
实例化并构造类myRectangle
的实例。相反,myRectangle mr ();
将mr
声明为返回myRectangle
且不带参数的函数。