Fra*_*nky 4 c++ copy-constructor
在X loc2 = loc;执行语句时,下面的代码中,编译器识别出下面的构造函数应该运行,然后运行它.
X(const X& x) { val = x.val; out("X(X&)"); }
我知道构造函数被认为是一个复制构造函数,但我的问题是编译器如何知道构造函数是该语句的?有没有关于复制构造函数的结构应该如何在执行复制语句时被识别和运行的规则?
#include "std_lib_facilities_4.h"
using namespace std;
struct X {
int val;
void out(const string& s)
{cerr << this << " -> " << s << ": " << val << "\n\n"; }
X(int v) { val = v; out("X(int)"); }
X(const X& x) { val = x.val; out("X(X&)"); } // The copy constructor
};
int main()
{
X loc(4);
X loc2 = loc; // This statement
char ch;
cin>>ch;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
std_lib_facilities就在这里.我使用的操作系统是Windows,我的编译器是Visual Studio.
只要构造函数具有以下形式之一,它将在编译时自动采用为复制构造函数:
X(const X& );
X(X&);
X(volatile X& );
X(const volatile X& );
X(const X&, /*any number of arguments with default values*/);
X(X&, /*any number of arguments with default values*/);
Run Code Online (Sandbox Code Playgroud)
采用第一个,除非你有充分的理由采用替代方案.
| 归档时间: |
|
| 查看次数: |
65 次 |
| 最近记录: |