首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C++为什么使用参数化构造函数时竟然没有编译错误?

C++为什么使用参数化构造函数时竟然没有编译错误?

提问于 2018-02-07 00:24:08
回答 2关注 0查看 764

我已经生成了下面的示例代码来说明我的问题:

代码语言:txt
复制
#include <string>
#include <iostream>

class MyException
{
    public:
        MyException(std::string s1) {std::cout << "MyException constructor, s1: " << s1 << std::endl;}
};

int main(){
    const char * text = "exception text";
    std::cout << "Creating MyException object using std::string(const char *)." << std::endl;
    MyException my_ex(std::string(text));
    std::cout << "MyException object created." << std::endl;
    //throw my_ex;

    std::string string_text("exception text");
    std::cout << "Creating MyException object using std::string." << std::endl;
    MyException my_ex2(string_text);
    std::cout << "MyException object created." << std::endl;
    // throw my_ex2;

    return 0;
}

此代码段编译时没有任何错误,并产生以下输出:

代码语言:txt
复制
 $ g++ main.cpp
 $ ./a.out
Creating MyException object using std::string(const char *).
MyException object created.
Creating MyException object using std::string.
MyException constructor, s1: exception text
MyException object created.

请注意,对于my_ex我定义的构造函数没有被调用。接下来,如果我真的想抛出这个变量:

代码语言:txt
复制
throw my_ex;

我得到一个编译错误:

代码语言:txt
复制
 $ g++ main.cpp
/tmp/ccpWitl8.o: In function `main':
main.cpp:(.text+0x55): undefined reference to `my_ex(std::string)'
collect2: error: ld returned 1 exit status

如果我在转换前后添加大括号,如下所示:

代码语言:txt
复制
const char * text = "exception text";
std::cout << "Creating MyException object using std::string(const char *)." << std::endl;
MyException my_ex((std::string(text)));
std::cout << "MyException object created." << std::endl;
throw my_ex;

然后它就像我所期望的那样起作用了:

代码语言:txt
复制
 $ g++ main.cpp
 $ ./a.out
Creating MyException object using std::string(const char *).
MyException constructor, s1: exception text
MyException object created.
terminate called after throwing an instance of 'MyException'
Aborted (core dumped)

我有以下问题:为什么我的第一个示例要编译?为什么我没有编译错误?

相关文章

相似问题

相关问答用户
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档