C
campos
Here are my codes:
#include <iostream>
using namespace std;
class Test
{
public:
Test() { cout << "Test()" << endl; }
Test(const string& s) { str = s; cout<< "Test(string)" << endl; }
Test(const Test& t) { str = s; cout << "Test(const Test&)" << endl;
}
private:
string str;
}
int main()
{
string str("hello");
Test t1(str);
Test t2 = str;
return 0;
}
I use VC++ 7.0 to compile and run the program, the result is:
-----------------
Test(string)
Test(string)
-----------------
copy constructor has not been called.
But in "C++ Primer 4th Edition", Ch 13.1
-----------------------------------------------------------
Usually the difference between direct- or copy-initialization is at
most a matter of low-level optimization. However, for types that do not
support copying, or when using a constructor that is nonexplicit
(Section 12.4.4, p. 462) the distinction can be essential:
ifstream file1("filename"); // ok: direct initialization
ifstream file2 = "filename"; // error: copy constructor is private
// This initialization is okay only if
// the Sales_item(const string&) constructor is not explicit
Sales_item item = string("9-999-99999-9");
#include <iostream>
using namespace std;
class Test
{
public:
Test() { cout << "Test()" << endl; }
Test(const string& s) { str = s; cout<< "Test(string)" << endl; }
Test(const Test& t) { str = s; cout << "Test(const Test&)" << endl;
}
private:
string str;
}
int main()
{
string str("hello");
Test t1(str);
Test t2 = str;
return 0;
}
I use VC++ 7.0 to compile and run the program, the result is:
-----------------
Test(string)
Test(string)
-----------------
copy constructor has not been called.
But in "C++ Primer 4th Edition", Ch 13.1
-----------------------------------------------------------
Usually the difference between direct- or copy-initialization is at
most a matter of low-level optimization. However, for types that do not
support copying, or when using a constructor that is nonexplicit
(Section 12.4.4, p. 462) the distinction can be essential:
ifstream file1("filename"); // ok: direct initialization
ifstream file2 = "filename"; // error: copy constructor is private
// This initialization is okay only if
// the Sales_item(const string&) constructor is not explicit
Sales_item item = string("9-999-99999-9");