代码之家  ›  专栏  ›  技术社区  ›  User12547645

C++:返回一个对象并将其分配给函数

  •  -1
  • User12547645  · 技术社区  · 8 年前

    我是C++的初学者,我想做如下事情:

    myObj f(){
        // do stuff 
        // return instance of myObj
    }
    
    int main(){
        // do stuff
        myObj mO = f(); 
    }
    

    我需要做什么,才能在C++中工作?

    我的想法是,我必须为myObj stuct/类实现一个赋值运算符,或者编写另一个类似于这样的构造函数 myObj::myObj(myObj mO){...} ,我是这样用的 myObj = myObj(f()); .

    对吗?

    我还需要做更多的事才能让这一切顺利吗?

    你能提供一个有效的例子吗?

    谢谢

    2 回复  |  直到 8 年前
        1
  •  0
  •   wally    8 年前

    这几乎可以按原样编译。

    //define a class
    class myObj {};
    
    // return an instance of the class
    myObj f() {
        return myObj{};
    }
    
    // call with the same main as in the question:
    int main(){
        // do stuff
        myObj mO = f(); 
    }
    
        2
  •  0
  •   6502    8 年前

    C++为您定义了一个复制构造函数、赋值运算符和移动构造函数(如果可以轻松完成);在这些情况下,您应该什么都不做,只需返回一个对象实例,调用者就会得到它。

    但是,如果对象有一些不能复制的部分(例如引用),那么您需要提供复制构造函数并自行赋值(但可能是确实不应该复制或赋值的类)。

    还有其他一些限制,阻止自动合成move构造函数(以避免bug)。

    还请注意,在某些情况下,C++编译器会合成复制构造函数和赋值,但使用了错误的代码。您需要小心(例如,如果类包含裸指针)。

    对于一个简单的情况,即一切都是开箱即用,不需要做任何事情,请考虑:

    // A bi-dimensional point
    struct P2d {
        double x, y;
    };
    
    // Computes the middle point given two points
    P2d average(P2d a, P2d b) {
        return P2d{(a.x+b.x)/2, (a.y+b.y)/2};
    }
    

    正如你所见,课堂上不需要任何东西来支持回归 P2d 价值观还是接受 P2d 参数。

    在这种情况下,编译器会自动完成定义代码,如下所示:

    struct P2d {
        double x, y;
    
        P2d(const P2d& other)
          : x(other.x), y(other.y)
        {
        }
    
        P2d& operator=(const P2d& other) {
            x = other.x;
            y = other.y;
            return *this;
        }
    
        ~P2d() {
        }
    };