Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何区分基本类型? 自从我从C到C++的转换,我对STL的格式输出有个问题。Ostream如何区分一种基本类型和另一种基本类型 在C中,用它的Prtf和格式化字符串是非常简单的,但是在C++中,OFFASH自动地区分基本类型。这让我困惑_C++_Types_Cout - Fatal编程技术网

如何区分基本类型? 自从我从C到C++的转换,我对STL的格式输出有个问题。Ostream如何区分一种基本类型和另一种基本类型 在C中,用它的Prtf和格式化字符串是非常简单的,但是在C++中,OFFASH自动地区分基本类型。这让我困惑

如何区分基本类型? 自从我从C到C++的转换,我对STL的格式输出有个问题。Ostream如何区分一种基本类型和另一种基本类型 在C中,用它的Prtf和格式化字符串是非常简单的,但是在C++中,OFFASH自动地区分基本类型。这让我困惑,c++,types,cout,C++,Types,Cout,例如,在下面的代码中 int i; float f; std::cout << i << std::endl; std::cout << f << std::endl; 怎么知道i是int,f是float?第二个参数到运算符的重载解析第二个参数到运算符的重载解析它是一个重载的ostream运算符它是一个重载的ostream运算符有运算符有运算符编译器将运算符转换为函数调用。所以 std::cout << i std::cout &

例如,在下面的代码中

int i;
float f;

std::cout << i << std::endl;
std::cout << f << std::endl;

怎么知道i是int,f是float?

第二个参数到运算符的重载解析第二个参数到运算符的重载解析它是一个重载的ostream运算符它是一个重载的ostream运算符有运算符有运算符编译器将运算符转换为函数调用。所以

std::cout << i
std::cout << i
产生产出:

5
7.700000
你自己试试看:

编辑:正如Jesse Good指出的,所讨论的函数是成员函数。因此,我们确实有:

变成

operator<<(std::cout, i)
std::cout.operator<<(i)
在标题中有相当于以下内容的声明:

std::ostream& operator<<(std::ostream& o, int i);
std::ostream& operator<<(std::ostream& o, double d);
class ostream {
    ostream& operator<<(int i);
    ostream& operator<<(double d);
    ...
};

然而,同样的基本思想也适用。

编译器将运算符转换为函数调用。所以

std::cout << i
std::cout << i
产生产出:

5
7.700000
你自己试试看:

编辑:正如Jesse Good指出的,所讨论的函数是成员函数。因此,我们确实有:

变成

operator<<(std::cout, i)
std::cout.operator<<(i)
在标题中有相当于以下内容的声明:

std::ostream& operator<<(std::ostream& o, int i);
std::ostream& operator<<(std::ostream& o, double d);
class ostream {
    ostream& operator<<(int i);
    ostream& operator<<(double d);
    ...
};

然而,同样的基本思想也适用。

函数重载是编译时多态性的一种形式。一个简单的例子:

void times_two(int& x) { x *= 2; }
void times_two(double& x) { x *= 2; }

int i = 2;
double d = 2.5;

times_two(i);  // i now 4
times_two(d);  // d now 5.0

对于std::ostream,例如std::cout,操作符函数重载是编译时多态性的一种形式。一个简单的例子:

void times_two(int& x) { x *= 2; }
void times_two(double& x) { x *= 2; }

int i = 2;
double d = 2.5;

times_two(i);  // i now 4
times_two(d);  // d now 5.0

在std::ostream(如std::cout)的情况下,运算符不是全部operator@JesseGood:说得好。所以我的例子在事实上并不完全正确。它基本上仍然是正确的,我觉得把它改成完美会模糊主要思想。更不用说试图描述std::endl实际上是如何编码的了…@Managu:当然有!它在编译时作为类模板basic_ostream:notall的实例化生成operator@JesseGood:说得好。所以我的例子在事实上并不完全正确。它基本上仍然是正确的,我觉得把它改成完美会模糊主要思想。更不用说试图描述std::endl实际上是如何编码的了…@Managu:当然有!它是在编译时作为类模板basic_ostream的实例化生成的:Streams从未和STL有过任何关系。你正在考虑C++标准库。Struts与STL从来没有任何关系。你在考虑C++标准库。