C + + implicit type conversion sample sharing _c language

Source: Internet
Author: User
Tags string format

Copy Code code as follows:

/*=============================================================================
# FileName:explicit_try.cc
# Desc: Verify that a non-explicit constructor with one parameter can be copied to initialize
=============================================================================*/
#include <iostream>
#include <string>
#include <vector>

Using Std::cout;
Using Std::cin;
Using Std::endl;
Using Std::string;
Using Std::vector;

class People {
Public
People () = default;
People (string s): Name (s) {}
String GetName () const {return name;}
Static vector<string> &getvector () {return name_arr;}
Implicit type conversions, which generate a temporary amount in string, so you can bind to a const parameter
static void Addtovector (const people &p) {
Name_arr.push_back (P.getname ());
}
Private
String name = "";
Static vector<string> Name_arr;
};

Vector<string> People::name_arr = {};

int main (int argc, const char *argv[])
{
People p;
cout << "P:" << Endl;
cout << p.getname () << Endl;
People Tom ("Tom");
People::addtovector (Tom);
string Bob = "Bob";
People::addtovector (BOB);//implicit type conversion
People::addtovector ("Bob");//Only one-step implicit type conversion is allowed

Vector<string> v = people::getvector ();
cout << "Name_arr:" << Endl;
for (const auto &P:V) {
cout << P << "";
}
cout << Endl;

String myname = "Guo";
People guo = myname; Implicit type conversions allow for conversion of copy initialization form
cout << guo.getname () << Endl;
return 0;
}



Here's another example.

Copy Code code as follows:

#include <string>
#include <iostream>
using namespace Std;
Class Fruit//define a category, named Fruit
{
String name; Define a name member
string colour; Define a colour member

Public
BOOL Issame (const Fruit &otherfruit)//expecting parameter is another Fruit class object that tests for the same name
{
return name = = Otherfruit.name;
}
void print ()///define member print for an output name ()
{
cout<<colour<< "" <<name<<endl;
}
Fruit (const string &nst,const string &cst = "Green"): Name (NST), colour (CST) {}//constructor

Fruit () {}
};

int main ()
{
Fruit Apple ("Apple");
Fruit Orange ("orange");
cout<< "Apple = orange?:" <<apple.issame (orange) <<endl; No problem, definitely different.
cout<< "Apple =/" apple/"?:" <<apple.issame (String ("Apple")); Use a string as a formal parameter?

return 0;
}

You will find that in the last use, we use a string type as an argument for a function that expects the fruit class parameter, and the result is true (1), don't be surprised, that's what I'm talking about, implicit class type conversions: " A constructor that can be invoked with a single argument defines an implicit conversion from the formal parameter type to that type. "(c + + Primer) First A single argument, you can remove the constructor colour default argument, that is, the definition of an object must be two parameters, file compilation can not pass. Then the system knows how to convert it, but it's more rigorous here: when we were building objects, fruit apple ("apple") had a conversion from the C string format of const char * to String, where You Apple.issame ("Apple"), the stupid system does not know how to help you convert two times, so you have to use String () to cast first, and then the system to help you from the string implicit conversion to fruit, of course, you can also help him to complete. cout<< "Apple =/" apple/"?:" <<apple.issame (Fruit ("Apple"));  Reference example 1.2:fruit Apple = Fruit ("Apple"); Defines an fruit class object, Apple. That's how it's converted. But this is called explicit conversion, we do not mark out, the system to help us complete, called the implicit shell. The point here is that if you show the transformation, you can do so regardless of the number of arguments, such as those mentioned above that require a constructor of two parameters.

Cases:

Copy Code code as follows:

#include <string>
#include <iostream>
using namespace Std;
Class Fruit//define a category, named Fruit
{
String name; Define a name member
string colour; Define a colour member

Public
BOOL Issame (const Fruit &otherfruit)//expecting parameter is another Fruit class object that tests for the same name
{
return name = = Otherfruit.name;
}
void print ()///define member print for an output name ()
{
cout<<colour<< "" <<name<<endl;
}
Fruit (const string &nst,const string &cst): Name (NST), colour (CST) {}//constructor

Fruit () {}
};

int main ()
{
Fruit Apple ("Apple", "green");
Fruit Orange ("orange", "Yellow");
cout<< "Apple = orange?:" <<apple.issame (orange) <<endl; No problem, definitely different.
cout<< "Apple =/" apple/"?:" <<apple.issame (Fruit ("Apple", "green"); Explicit conversions
return 0;
}


What if you don't want the implicit conversion to prevent the user from doing wrong? C + + provides a way to suppress the implicit conversion of a constructor, which is to add the explicit keyword in front of the constructor, and you will try to know that at that time you want the implicit conversion to cause the compilation to fail, but the explicit conversion is still possible.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.