简体   繁体   English

如何从静态成员函数返回副本?

[英]How do you return a copy from a static member function?

What's wrong with my static topStock method? 我的静态topStock方法有什么问题? It takes in a reference to Stock s and Stock t. 它引用了Stock和Stock t。 Shouldn't it return a copy of s or t? 它不应该返回s或t的副本吗?

error: expected primary-expression before '.' 错误:“。”之前的预期主表达式 token| 令牌|

#include <iostream>

using namespace std;

class Stock {

public:

    Stock() : x(0){ }
    Stock(int val) : x(val){}

    void display() const;

    static Stock topStock(const Stock& s, const Stock& t) {
     if (s.x > t.x)
        return s;
    else
        return t;
    }

    int x;
};

void Stock::display() const
{

    std::cout << this->x;

}


int main()
{
    Stock s(9);
    Stock y(8);
    Stock z = Stock.topStock(s, y);
    return 0;
}

Change 更改

Stock.topStock(s, y);

to

Stock::topStock(s, y);

because it is a static member function. 因为它是静态成员函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM