小编dal*_*ngh的帖子

列表初始化时需要缩小转换范围

我在 cpp 参考网站上读到了有关缩小转换的内容。我有点理解它,但我不明白的是为什么错误只出现在第一行。

    long double ld = 3.1415926536;
    int a{ld}, b = {ld}; // error: narrowing conversion required
    int c(ld), d = ld;   // ok: but value will be truncated
Run Code Online (Sandbox Code Playgroud)

为什么错误只出现在第一行而不是第二行?

c++ c++11 list-initialization type-narrowing

5
推荐指数
1
解决办法
423
查看次数

函数在C++中返回"This"对象

因此,以下是Class Sales_data的成员函数,它在类外定义,

Sales_data& Sales_data::combine(const Sales_data &rhs) {
    units_sold += rhs.units_sold;
    revenue += rhs.revenue; //adding the members of rhs into the members of "this" object
    return *this;
} //units_sold and revenue are both data members of class
Run Code Online (Sandbox Code Playgroud)

当调用该函数时,它被称为

total.combine(trans); //total and trans are the objects of class
Run Code Online (Sandbox Code Playgroud)

我不理解的是函数返回*this,我理解它返回一个对象的实例,但是它没有将这个实例返回给我们在函数调用期间可以看到的任何东西,如果我不写return语句,它会工作吗任何不同.

有人请详细解释,因为我只是没有得到它.

c++ return this this-pointer

3
推荐指数
1
解决办法
263
查看次数

引用指针

我只是在两个陈述之间有点困惑.

1.

    int a = 42;
    int *p = &a; //declares pointer p to a
    int &r = *p; //this is not the way to declare a reference to a pointer, but what does this statement do
Run Code Online (Sandbox Code Playgroud)

要打印价值,可以通过以下方式完成

    cout << a << *p << r;
Run Code Online (Sandbox Code Playgroud)

以上所有将打印a的值,但是如何,这就是我想知道的.

  1. 现在,这是如何定义对指针的引用

    int i = 42;
    int *p;
    int *&r = p; //declares reference r to pointer p
    r = &i; //stores the address of i in pointer p
    
    Run Code Online (Sandbox Code Playgroud)

我只想了解为什么第一个没有定义对指针的引用.

c++ pointers reference

1
推荐指数
1
解决办法
77
查看次数