标签:
如果构造函数只接受一个实参,则它实际上定义了转换为此类类型的隐式转换机制。将这种构造函数称为转换构造函数。
#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED
#include <iostream>
using namespace std;
class ClassTest
{
public:
ClassTest()
{
cout << "ClassTest()" <<endl;
}
ClassTest(int i)
{
cout << "ClassTest(int)" <<endl;
value = i;
value2 = 2;
}
ClassTest(int i, int j): value(i), value2(j)
{
cout << "ClassTest(int, int)" <<endl;
}
ClassTest(const ClassTest& test)
{
cout << "ClassTest(const ClassTest&)" << endl;
value = test.value;
value2 = test.value2;
}
void getValue(int &, int &);
private:
int value = 0;
int value2 = 0;
};
#endif // MAIN_H_INCLUDED
#include "main.h"
void ClassTest::getValue(int &iValue, int &iValue2)
{
iValue = value;
iValue2 = value2;
}
int main()
{
ClassTest classTest = 2;
/**
* 还可以使用以下几种实现方法
* ClassTest classTest(2);
* ClassTest classTest = ClassTest(2);
* ClassTest classTest = (ClassTest)2;
*/
int value = 0;
int value2 = 0;
classTest.getValue(value, value2);
cout << "value = " << value << "\nvalue2 = " << value2 << endl;
return 0;
}
#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED
#include <iostream>
using namespace std;
class ClassTest
{
public:
ClassTest()
{
cout << "ClassTest()" <<endl;
}
ClassTest(string str)
{
strValue = str;
}
string getValue()
{
return strValue;
}
private:
string strValue;
};
#endif // MAIN_H_INCLUDED
#include "main.h"
int main()
{
ClassTest classTest = string("Hello world!");
//ClassTest classTest = "Hello world!";/*无法实现从char[]先转化为string,在由string转换为类类型*/
cout << classTest.getValue() << endl;
return 0;
}
#ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED
#include <iostream>
using namespace std;
class ClassTest
{
public:
ClassTest()
{
cout << "ClassTest()" << endl;
}
/**
* 如果是在类声明之外进行类成员函数的实现,explicit只加在声明的位置
*/
ClassTest(string str)
{
strValue = str;
}
string getValue()
{
return strValue;
}
private:
string strValue;
};
#endif // MAIN_H_INCLUDED
#include "main.h"
int main()
{
//ClassTest classTest = string("Hello world!");/**< 错误 */
ClassTest classTest(string("hello world"));/**< 只能用于直接初始化 */
//ClassTest classTest = "Hello world!";/*无法实现从char[]先转化为string,在由string转换为类类型*/
cout << classTest.getValue() << endl;
return 0;
}
标签:
原文地址:http://www.cnblogs.com/fengkang1008/p/4652252.html