小编Mar*_*ian的帖子

完美转发返回值?

我正在重载一个operator[]

const Type&& operator[](int index) const {
        if (index >= size) { std::cout << "Error: excessive index.\n"; return 0; }
        else if (index < 0) { std::cout << "Error: negative index.\n"; return 0; }
        else {
            Node* temp = head->next;
            for (int i = 0; i < index; i++) { temp = temp->next; }
            return temp->value;
        }
    }
Run Code Online (Sandbox Code Playgroud)

但我需要它的副本,它将返回非常量类型值。我读到我们可以在函数参数可以是常量或非常量的情况下使用完美转发(以便我们forward<Type>每次使用它时都将它们包装起来),但是如何将它用于返回的值?

另外,如果我只想什么都不返回,我应该写return 0;还是return NULL;?哪个更容易理解?

c++ perfect-forwarding

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

虚拟重载运算符 &gt;&gt; 和 &lt;&lt;

我需要一个需要其子类重载<<and的接口>>,但我不太确定如何重载,因为这些运算符没有作为成员函数重载:

std::istream& operator>> (std::istream& in, Student& student) {
    in >> student.name >> student.group;
    for (int& i : student.marks) { in >> i; }
    return in;
} 
Run Code Online (Sandbox Code Playgroud)

也许有办法使它成为成员函数?

c++ virtual class operator-overloading function-definition

3
推荐指数
2
解决办法
107
查看次数

std::cout 中的三元条件运算符

这是我的代码:

std::cout << "The contaner is " << (!container)?"not":; "empty";
Run Code Online (Sandbox Code Playgroud)

这显然不起作用,但我希望现在这个想法很清楚。我想打印"The container is empty",并"not""empty"if bool containeris之前添加false

我想知道是否有可能,或者我是否必须按照以下方式写一些东西:

if(container) std::cout ...;
else std::cout ...; 
Run Code Online (Sandbox Code Playgroud)

c++ cout conditional-operator

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

使用 std::accumulate 求数组之和

这是我的数组:

std::array<int, 4> mark;
Run Code Online (Sandbox Code Playgroud)

这是我有的一个功能:

float getAverage() {
        float sum = 0;
        sum = std::accumulate(mark, mark + mark.size(), 0);
        return sum /= mark.size();
    }
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

Invalid operands to binary expression ('std::array<int, markAmount>' and 'std::__1::array::size_type' (aka 'unsigned long'))
Run Code Online (Sandbox Code Playgroud)

这是可以理解的,因为markmark.size()有不同的类型,但我不明白如何以其他方式制作它。我应该转换他们的类型吗?但为什么它不自动生成呢?类似于?array&array[0]因为这就是我所需要的std::accumulate

c++

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