小编hjj*_*200的帖子

班级内的操作员如何工作?

class A {
public:
    string operator+( const A& rhs ) {
        return "this and A&";
    }
};

string operator+( const A& lhs, const A& rhs ) {
    return "A& and A&";
}

string operator-( const A& lhs, const A& rhs ) {
    return "A& and A&";
}

int main() {
    A a;
    cout << "a+a = " << a + a << endl;
    cout << "a-a = " << a - a << endl;
    return 0;
}

//output
a+a = …
Run Code Online (Sandbox Code Playgroud)

c++ operator-overloading operators

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

如何正确va_end?

#include <cstdarg>
using namespace std;

void do_something( va_list numbers, int count ) {
//                         ^
// Should I call this by reference here? I mean, va_list & numbers?
    //... stuff
    va_end( numbers );
}

void setList( int count, ... ) {
    va_list numbers;
    va_start( numbers, count );
    do_something( numbers, count );
}

int main() {
    setList( 2, 0, 1 );
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

va_list进入另一个函数时,我应该如何将它传递给该函数?我知道va_end必须在完成任务时调用va_list我很困惑我是否应该通过引用来调用它.va_list即使没有通过引用调用,它也会正确结束吗?

c++ variadic-functions

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

如何防止重复长rvalue

int main() {
    int x = 1, y = 2, z = 3, w = 4;
#define formula x + y * z % w
    x++;
    do_something1(formula);
    y++;
    do_something2(formula);
    z++;
    do_something3(formula);
    w++;
    do_something4(formula);
#undef formula
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我目前正在使用#define以防止重复长rvalue.有没有更好的替代方法来做到这一点?

c++ coding-style rvalue

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

为什么析构函数会在这里被调用两次?

#include <iostream>

struct ABC{
    int A;
    ABC(int i = 1) : A(i) {}
    ~ABC() {
        std::cout << A << std::endl;
    }
    void destruct() {
        delete this;
    }
};

int main() {
    ABC A1(2);
    A1.destruct();
    return 0;
}

Output:
2
2
Run Code Online (Sandbox Code Playgroud)

我有这个代码,我试图手动删除结构变量.这样做,我意识到析构函数在这里被调用了两次.为什么会这样?destruct()调用时为什么不删除?

c++ struct destructor

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