Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.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++ - Fatal编程技术网

C++ 即使我传递了一个无效的类型参数,为什么我可以编译这段代码而不出错呢?

C++ 即使我传递了一个无效的类型参数,为什么我可以编译这段代码而不出错呢?,c++,C++,“func”将类C的常量引用作为其参数。 但我错误地将字符串传递给了它 我预计会出现类似“无匹配函数…”“无已知转换…”的错误,但编译已完成,没有任何错误,程序出现分段错误 为什么即使函数的参数不正确,编译器也不会导致错误 编译器版本 clang++3.9.1 g++6.3.1 #include <iostream> #include <string> class C ; void func( const C &_c ) {} class C { publi

“func”将类C的常量引用作为其参数。 但我错误地将字符串传递给了它

我预计会出现类似“无匹配函数…”“无已知转换…”的错误,但编译已完成,没有任何错误,程序出现分段错误

为什么即使函数的参数不正确,编译器也不会导致错误

编译器版本 clang++3.9.1 g++6.3.1

#include <iostream>
#include <string>

class C ;

void func( const C &_c )
{}

class C
{
public :
    C( const std::string &_s )
    {
        func( _s ) ;
    }
} ;

int main()
{
    C c( "foo" ) ;
}
#包括
#包括
丙级;;
无效函数(常数C和C)
{}
C类
{
公众:
C(常数std::string&\u s)
{
func(s),;
}
} ;
int main()
{
C C(“foo”);
}

由于您有一个构造函数可以从
std::string
生成
C
,因此它基本上编译了您的
func(
),就好像它是
func(C(\us))
一样。很明显,这会导致无限的递归和崩溃程序(因为该函数是你现在的函数),但是技术上它不是无效的C++,所以编译器允许它。如果你不想这样做,你可以声明你的构造函数
显式
,这意味着编译器永远不会使用它,除非你显式调用它。

因为你有一个构造函数可以从
std::string
生成
C
,它基本上编译了你的
func(\u s)
,就好像它是
func一样(C(_s))
。很明显,这只会导致无限递归并使程序崩溃(因为该函数就是您现在使用的函数)如果你不想让它工作,你可以声明你的构造函数<代码>显式< /C> >,这意味着除非你明确地调用它,否则编译器永远不会使用它。

如果它无效,编译器就要做什么?假装它是有效的吗?你通过了一个C++版本。e> std::string
传递给需要
C
的对象。是否正在寻找模板函数?如果它无效,则它无效。您希望编译器做什么?假装它有效?您正在将
std::string
传递给需要
C
的对象。是否正在寻找模板函数?